Cryptography Reference
In-Depth Information
//zero is a special case-nothing to do but return a copy of the
//nonzero Int
if (this.equals(ZERO)) return new Int(other);
else if (other.equals(ZERO)) return new Int(this);
else if (this.equals(other.negative())) return new Int();
//If they are the same sign, perform the addition; add carries
else if (negative==other.negative) {
ans=addDigits(other);
ans.negative=negative;
}
//If they are of different signs, determine the larger
//(magnitude-wise) and subtract the smaller from it.
//Result has same sign as first (larger) operand.
else if (this.absoluteValue().lessThan(other.absoluteValue())) {
ans=other.subtractDigits(this);
ans.negative=other.negative;
} else {
ans=this.subtractDigits(other);
ans.negative=this.negative;
}
//Trim leading zeros and return
return ans.trimZeros();
}
public Int subtract(Int other) {
//To subtract, we add the negative
return this.add(other.negative());
}
private Int addDigits(Int other) {
int top1=this.digits.length-1;
int top2=other.digits.length-1;
int top3=Math.max(this.digits.length,other.digits.length)+1;
Int answer=new Int();
answer.digits=new int[top3];
top3--;
int carry=0; int sum=0;
while (top1>=0&&top2>=0) {
sum=this.digits[top1]+other.digits[top2]+carry;
if (sum>9) {sum%=10; carry=1;} else carry=0;
answer.digits[top3]=sum;
top1--;top2--;top3--;
}
if (top1<0&&top2<0) {
answer.digits[0]=carry;
} else if (top1<0) {
Search WWH ::




Custom Search