Given two non-negative integers a and b, the task is to calculate a raised to the power b without using the multiplication (*) and division (/) operators.
- Multiplication can be replaced with repeated addition to calculate the power.
- The same idea can be implemented using loops or recursion.
Example
For a = 5 and b = 3:
5^3 = 5 × 5 × 5 = 125
Approaches to Find Power Without Multiplication and Division
The power can be calculated using the following approaches:
1. Using Nested Loops
The idea is to replace every multiplication with repeated addition. For each power, the previous result is added a times.
For example, to calculate 5^3:
- Add 5 five times to get 25 (5^2).
- Add 25 five times to get 125 (5^3).
#include <bits/stdc++.h>
using namespace std;
// Works only if a >= 0 and b >= 0
int pow(int a, int b)
{
if (b == 0)
return 1;
int answer = a;
int increment = a;
for (int i = 1; i < b; i++)
{
for (int j = 1; j < a; j++)
{
answer += increment;
}
increment = answer;
}
return answer;
}
// Driver Code
int main()
{
cout << pow(5, 3);
return 0;
}
Output
125
Explanation
- answer stores the current power, while increment stores the value that is repeatedly added.
- The outer loop calculates each successive power, and the inner loop performs multiplication using repeated addition.
- When b is 0, the function returns 1 because a^0 = 1.
2. Using Recursion
The multiplication of two numbers is first implemented using recursive addition. This multiplication function is then used recursively to calculate the power.
#include <bits/stdc++.h>
using namespace std;
// Recursive function to calculate x * y
// using addition
int multiply(int x, int y)
{
if (y)
return x + multiply(x, y - 1);
else
return 0;
}
// Recursive function to calculate a^b
// Works only if a >= 0 and b >= 0
int pow(int a, int b)
{
if (b)
return multiply(a, pow(a, b - 1));
else
return 1;
}
// Driver Code
int main()
{
cout << pow(5, 3);
return 0;
}
Output
125
Explanation
- multiply() calculates x × y by recursively adding x, y times.
- pow() recursively calculates a^b and uses multiply() instead of the multiplication operator.
- The recursion stops when b becomes 0, returning 1.