Compute the product a * b given two integers a and b without using the multiplication (*), division (/), bitwise operators, or explicit loops. You may use recursion and addition or other allowed mathematical identities.
Multiplication is repeated addition: a * b equals adding a to itself |b| times. If loops are not allowed, recursion performs the same repeated-step behaviour implicitly via the call stack.
classSolution {
public:// non-static public method
int multiply(int a, int b) {
if (b ==0) return0;
if (b >0) return a + multiply(a, b -1);
return-multiply(a, -b);
}
};
1
2
3
4
5
6
7
8
9
10
packagemaintypeSolutionstruct{}
// Multiply is a public method on Solutionfunc (sSolution) Multiply(a, bint) int {
ifb==0 { return0 }
ifb > 0 { returna+s.Multiply(a, b-1) }
return-s.Multiply(a, -b)
}
1
2
3
4
5
6
7
classSolution {
publicintmultiply(int a, int b) {
if (b == 0) return 0;
if (b > 0) return a + multiply(a, b - 1);
return-multiply(a, -b);
}
}
1
2
3
4
5
6
7
classSolution:
defmultiply(self, a: int, b: int) -> int:
if b ==0:
return0if b >0:
return a + self.multiply(a, b -1)
return-self.multiply(a, -b)
Use the identity (a + b)^2 = a^2 + b^2 + 2ab to express ab = ((a+b)^2 - a^2 - b^2) / 2. If direct division is not allowed, compute division by two using a recursive divide_by_2 that subtracts 2 repeatedly.
classSolution {
public:int divideBy2(int n) {
if (n <2) return0;
return1+ divideBy2(n -2);
}
// non-static public multiply
intmultiply(int a, int b) {
int whole = (a + b) * (a + b);
int aa = a * a;
int bb = b * b;
int val = whole - aa - bb;
if (val >=0) return divideBy2(val);
return-divideBy2(-val);
}
};
classSolution {
intdivideBy2(int n) {
if (n < 2) return 0;
return 1 + divideBy2(n - 2);
}
publicintmultiply(int a, int b) {
int whole = (a + b) * (a + b);
int aa = a * a;
int bb = b * b;
int val = whole - aa - bb;
if (val >= 0) return divideBy2(val);
return-divideBy2(-val);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution:
defdivide_by_2(self, n: int) -> int:
if n <2:
return0return1+ self.divide_by_2(n -2)
defmultiply(self, a: int, b: int) -> int:
whole = (a + b) * (a + b)
aa = a * a
bb = b * b
val = whole - aa - bb
if val >=0:
return self.divide_by_2(val)
return-self.divide_by_2(-val)