Java help!!! Im working on adding and subtrcating two 40 element arrays. Ive alr
ID: 667670 • Letter: J
Question
Java help!!! Im working on adding and subtrcating two 40 element arrays. Ive already written my add and subract methods but im havng trouble handling the negatives.I need to write a negate function! For example if i have 8+(-15) I need the negate to implement propery. this is the code i have to add onto.Please help with the negate function!
public void add(HugeInteger hi){
if(positive!=hi.positive){
if(this.positive){
hi.negate(); //
if(this.isGreaterThan(hi)){
// |this| > |hi| [example: 8+(-5)]
this.digits = subtractArrayDigits(this.digits, hi.digits);
}
else { // example 8+(-15)
// |this| <= |hi| [example: 8+(-15)]
this.digits = subtractArrayDigits(hi.digits, this.digits);
// negate the "this"
negate();// added
}
hi.negate(); // restore hi's sign
}
else {
}
}else{
// same sign, easy :)
digits = addArrayDigits(this.digits, hi.digits);
}
}
Im confused on the negate method!!!
Explanation / Answer
//this -= hi
public void subtract(HugeInteger hi){
//if the signs of the two numbers are not the same
if(this.positive != hi.positive){
// 'this' is positive...
if (this.positive){
// negates hi temporarily.
hi.negate();
//if this is greater than hi..
if (this.isGreaterThan(hi)){
this.digits = addArrayDigits(this.digits, hi.digits);
//otherwise this is less than or equal to hi
}else{
this.digits = addArrayDigits(hi.digits, this.digits);
this.negate();
}
// 'this' sign is reverted back to original.
hi.negate();
//now hi is positive while this is negative...
}else{
// this is negated temporarily.
this.negate();
//if this is greater than hi...
if (this.isGreaterThan(hi)){
this.digits = addArrayDigits(this.digits, hi.digits);
//otherwise....this is less than or equal to hi...
}else{
this.digits = addArrayDigits(hi.digits, this.digits);
}//end inner if-else
// hi is reverted back to original sign.
this.negate();
}//end if-else
}else if(this.positive == true){
if(this.isGreaterThan(hi)){
this.digits = subtractArrayDigits(this.digits, hi.digits);
}else{
this.digits = subtractArrayDigits(hi.digits, this.digits);
this.negate();
}//end if-else
//if both are negative
}else{
if(this.isGreaterThan(hi)){
this.digits = subtractArrayDigits(hi.digits, this.digits);
this.negate();
}else{
this.digits = subtractArrayDigits(this.digits, hi.digits);
}//end if-else
}//end outer if-else if-else
//end subtract
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.