Cryptography Reference
In-Depth Information
n.digits[pos]—;
}
//Method to chop off any leading zeros
private Int trimZeros() {
int i;
//Look for first nonzero in the array
for (i=0;i<this.digits.length;i++)
if (this.digits[i]!=0)
break;
Int answer=new Int();
answer.negative=this.negative;
//Make a (possibly) smaller array for answer
answer.digits=new int[this.digits.length-i];
//Copy the nonzero digits over, and return answer
for (int j=0;j<answer.digits.length;j++)
answer.digits[j]=this.digits[j+i];
return answer;
}
Methods to multiply and divide Ints should also be written. We will develop the multi-
ply(Int) method here. When we multiply two integers, we really just multiply by a single digit
at a time, then perform a total of these individual products. For example, when we do
527
613
we actually do these separate products:
527
6 = 3162, 527
1 = 527, and 527
3 = 1581.
We then add these products together, shifting some of the products to the left. That is, we
append a zero to 527 1 since 1 is in the tens column, and we append two zeros to 526
6 because 6 is in the hundreds column: This gives us
527
x 613
1581
+ 5270
+ 316200
323051
Thus our multiplication problem actually becomes an addition problem, as long as we
are able to multiply an integer by a single digit, and as long as we can append a certain
number of zeros to our sub-products. Doing the latter in Java is very simple, as you can see
from the following code:
Search WWH ::




Custom Search