Cryptography Reference
In-Depth Information
2.3
ARITHMETIC METHODS
Of course, we must write methods to perform arithmetic with Int objects. We must be able
to add, subtract, multiply, and divide. For convenience, we should add methods to increment
and decrement Int objects. First, we consider the addition of two integers
a
and
b
:
• If one is zero, return the other as the answer. Otherwise go on.
• If
, return zero. Otherwise go on.
• If the digits are the same sign, add them beginning with the lowest digits, adding any car-
ries in the subsequent addition. Otherwise go on.
• If the digits are of different signs, this is a subtraction; either
a
=
b
. To do a
subtraction, you must determine the larger of the two integers without regard to sign, then
subtract the smaller integer from the larger. The sign of the answer is the same as that of
the larger operand.
a
-
b
or
b
-
a
We shouldn't be too surprised at this addition/subtraction scheme, because it is the way
humans (using base 10) normally do it. Notice that writing the add(Int) and subtract(Int) may
entail using some of the methods already developed (like equals(Int) and lessThan(Int)),
and may require writing a few more methods as well. For instance, in the following there
is a method to negate an Int, and one to produce the absolute value. These are listed first.
public Int absoluteValue() {
//Make a new Int by copying this Int
Int answer=new Int(this);
//Set negative to false
answer.negative=false;
return answer;
}
public Int negative() {
Int answer=new Int(this);
//Flip the negative value
answer.negative=!this.negative;
return answer;
}
The code which does most of the work is in the add(Int) method. First, it determines the
sign of the two numbers; if they are the same, it is an addition problem, and the addDigits(Int)
method is called. If they are not the same, it is a subtraction problem, and the subtractDig-
its(Int) method is called. The subtractDigits(Int) method may call the borrow(Int) method,
which allows us to borrow from digits to the left for subtraction. Of course, after the num-
bers are added or subtracted, there may be leading zeros, which should be removed.
public Int add(Int other) {
Int ans;
Search WWH ::




Custom Search