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)

The solution is based on 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.

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz