![]() |
VOOZH | about |
By making use of recursion, we can multiply two integers with the given constraints.
To multiply x and y, recursively add x y times.
Approach:
Since we cannot use any of the given symbols, the only way left is to use recursion, with the fact that x is to be added to x y times.
Base case: When the numbers of times x has to be added becomes 0.
Recursive call: If the base case is not met, then add x to the current resultant value and pass it to the next iteration.
-55
Time Complexity: O(y) where y is the second argument to function multiply().
Auxiliary Space: O(y) for the recursion stack
Another approach: The problem can also be solved using basic math property
(a+b)2 = a2 + b2 + 2a*b
⇒ a*b = ((a+b)2 - a2 - b2) / 2
For computing the square of numbers, we can use the power function in C++ and for dividing by 2 in the above expression we can write a recursive function.
Below is the implementation of the above approach:
-55
Time complexity: O(num)
Auxiliary space: O(num) for recursive call stack
Russian Peasant (Multiply two numbers using bitwise operators)
Please write comments if you find any of the above code/algorithm incorrect, or find better ways to solve the same problem.