Topic 7.4 Write methods to implement the multiply, subtract, and divide operations for integers. Use only the add operator.
First ask: is this for int? If no, it is not easy to multiply float or double.
1) 减法:Just do a+(-b). 因为不能用-1乘以b,所以只好写一个把b变成负的方法。用加法,从0一个一个加-1,直到从a一个一个加-1=0为止
2) 乘法:a*b=add a to itself b times.
Improve: if a<b, add b a times; if a>b, add a b times, this can save some time.
3) 除法:b can’t be zero. a might not be evenly divisible by b, that is OK, because Integer division, is the floor of result.
public class c7_4 {
public static int negate(int a) {//这个变负的办法很神奇
int neg = 0;
int d = a < 0 ? 1 : -1;
while (a != 0) {
neg += d;
a += d;
}
return neg;
}
public static int minus(int a, int b) {
return a + negate(b);
}
/* Return absolute value */
public static int abs(int a) {
if (a < 0) {
return negate(a);
}
else return a;
}
/* Multiply a by b by adding a to itself b times */
public static int multiply(int a, int b) {
if (a < b) {
return multiply(b, a); // algo is faster if b < a
}
int sum = 0;
for (int i = abs(b); i > 0; i--) {
sum += a;
}
if (b < 0) {
sum = negate(sum);
}
return sum;
}
public static int divide(int a, int b) throws java.lang.ArithmeticException {
if (b == 0) {
throw new java.lang.ArithmeticException("ERROR: Divide by zero.");
}
int absa = abs(a);
int absb = abs(b);
int product = 0;
int x = 0;
while (product + absb <= absa) { /* don't go past a */
product += absb;
x++;
}
if ((a < 0 && b < 0) || (a > 0 && b > 0)) {
return x;
} else {
return negate(x);
}
}
public static void main(String[] args) {
System.out.println(negate(5));
System.out.println(minus(7,5));
System.out.println(multiply(7,5));
System.out.println(divide(7,5));
}
}
//结果
-5
2
35
1