Multiply two numbers without using multiplication operator or loops

Given two integers, multiply them without using multiplication operator or conditional loops.

 
Method 1: (using Recursion)

The idea is that for given two numbers a and b, we can get a*b by adding integer a exactly b times to the result.

C++ implementation –
 

Download   Run Code

Output:

12 12 -12 -12

 
Method 2: (Iterative using Bitwise operators)

If loops are allowed, we can use below relation –

multiply(a, b) = | multiply(a*2, b/2) if b is even
                 | b + multiply(a*2, b/2) if b is odd

 
C++ implementation –
 

Download   Run Code

Output:

12 12 -12 -12

The recursive version of above solution is left as an exercise to the readers.

 
1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)

Loading...

Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
newest oldest most voted
Notify of
Pete
Guest

Uh, ok:
a * b = b != 0 ? a/(1/b) : 0

Done. Handle division by zero.