Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiply two numbers without using multiplication [closed]

I have a test, where I needed to code for multiplying two numbers without using multiplication,

the code is as follows,

function multiply(num,toNum){
  var product = 0;
  for(var i = 1; i <= toNum; i++){
    product += num;
  }

  return product;
}

console.log(multiply(2,5)); 

The output is

rahul@rahul:~/myPractise/Algo$ node MultiplyWithoutLoop.js 
10 
rahul@rahul:~/myPractise/Algo$ 

Is the above code satisfactory or need is there a room for improvement.

Can a better logic be applied.

Hey,

I solved it using recursion,

this is the code,

function multiply01(num,toNum){
  var product = num;    
  return (toNum >= 1) ? product + multiply01(product,--toNum) : 0; 
}
like image 385
Rahul Shivsharan Avatar asked Aug 27 '26 11:08

Rahul Shivsharan


2 Answers

Compact way:

function multiply(a, b) {
  return a / (1 / b);
}

console.log(multiply(2, 5)); // 10
like image 60
Andrey Etumyan Avatar answered Aug 29 '26 01:08

Andrey Etumyan


You could use addition for odd numbers and and bit shifting. Better known as Ancient Egyptian multiplication.

The value of b is summed, if a is odd. Then a is divided by 2 and the integer part is assigned. b is doubled.

Example:

 a    b   sum
---  ---  ---
  5    4    4  add 4
  2    8    4
  1   16   20  add 16
  0   32   20  <- result

function multiply(a, b) {
    var sum = 0;
    while (a) {
        if (a & 1) {
            sum += b;
        }
        a >>= 1;
        b <<= 1;
    }
    return sum;
}

console.log(multiply(5, 4));
console.log(multiply(3, 7));
console.log(multiply(191, 7));
like image 38
Nina Scholz Avatar answered Aug 29 '26 01:08

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!