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

1. Using Recursion

The idea is that for given two numbers a and b, we can get a×b by adding an integer a exactly b times to the result. This approach is demonstrated below in C++, Java, and Python:

C++


Download  Run Code

Output:

12 12 -12 -12

Java


Download  Run Code

Output:

12 12 -12 -12

Python


Download  Run Code

Output:

12
12
-12
-12

2. Iterative solution using Bitwise operators

If loops are allowed, we can use the following relation:

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

The implementation can be seen below in C++, Java, and Python:

C++


Download  Run Code

Output:

12 12 -12 -12

Java


Download  Run Code

Output:

12 12 -12 -12

Python


Download  Run Code

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