I had an interesting interview yesterday where the interviewer asked me a classic question: How can we multiply two numbers in Java without using the *
operator. Honestly, I don't know if it's the stress that comes with interviews, but I wasn't able to come up with any solution.
After the interview, I went home and breezed through SO for answers. So far, here are the ones I have found:
First Method: Using a For loop
// Using For loop public static int multiplierLoop(int a, int b) { int resultat = 0; for (int i = 0; i < a; i++) { resultat += b; } return resultat; }
Second Method: Using Recursion
// using Recursion public static int multiplier(int a, int b) { if ((a == 0) || (b == 0)) return 0; else return (a + multiplier(a, b - 1)); }
Third Method: Using Log10
**// Using Math.Log10 public static double multiplierLog(int a, int b) { return Math.pow(10, (Math.log10(a) + Math.log10(b))); }**
So now I have two questions for you:
First Method: Using Recursion to multiply two numbers without using *. We can easily calculate the product of two numbers using recursion without using * multiplication operator. // If second number is zero then the product is zero. // Add first num, until second num is equal to zero.
The multiplication of two numbers can be found by the repeated addition method. It means that add the number (multiplicand) into itself up to multiplicator times.
I don't know whether that has to be a strictly "programming question". But in Maths:
x * y = x / (1 / y) #divide by inverse
So:
Method 1:
public static double multiplier(double a, double b) { // return a / (1 / b); // the above may be too rough // Java doesn't know that "(a / (b / 0)) == 0" // a special case for zero should probably be added: return 0 == b ? 0 : a / (1 / b); }
Method 2 (a more "programming/API" solution):
Use big decimal, big integer:
new BigDecimal("3").multiply(new BigDecimal("9"))
There are probably a few more ways.
There is a method called Russian Peasant Multiplication. Demonstrate this with the help of a shift operator,
public static int multiply(int n, int m) { int ans = 0, count = 0; while (m > 0) { if (m % 2 == 1) ans += n << count; count++; m /= 2; } return ans; }
The idea is to double the first number and halve the second number repeatedly till the second number doesn’t become 1. In the process, whenever the second number become odd, we add the first number to result (result is initialized as 0) One other implementation is,
static int russianPeasant(int n, int m) { int ans = 0; while (m > 0) { if ((m & 1) != 0) ans = ans + n; n = n << 1; m = m >> 1; } return ans; }
refer :
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With