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;
}
Compact way:
function multiply(a, b) {
return a / (1 / b);
}
console.log(multiply(2, 5)); // 10
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));
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