C++ Program To Find Power Without Using Multiplication(*) And Division(/) Operators
Method 1 (Using Nested Loops):
We can calculate power by using repeated addition.Â
For example to calculate 5^6.Â
1) First 5 times add 5, we get 25. (5^2)Â
2) Then 5 times add 25, we get 125. (5^3)Â
3) Then 5 times add 125, we get 625 (5^4)Â
4) Then 5 times add 625, we get 3125 (5^5)Â
5) Then 5 times add 3125, we get 15625 (5^6)Â
C++
#include <bits/stdc++.h>
using namespace std;
int pow ( int a, int b)
{
if (b == 0)
return 1;
int answer = a;
int increment = a;
int i, j;
for (i = 1; i < b; i++)
{
for (j = 1; j < a; j++)
{
answer += increment;
}
increment = answer;
}
return answer;
}
int main()
{
cout << pow (5, 3);
return 0;
}
|
Output :Â
125
Time Complexity: O(a * b)
Auxiliary Space: O(1)
Method 2 (Using Recursion)Â
Recursively add a to get the multiplication of two numbers. And recursively multiply to get a raise to the power b.
C++
#include<bits/stdc++.h>
using namespace std;
int multiply( int x, int y)
{
if (y)
return (x + multiply(x,
y - 1));
else
return 0;
}
int pow ( int a, int b)
{
if (b)
return multiply(a,
pow (a, b - 1));
else
return 1;
}
int main()
{
cout << pow (5, 3);
getchar ();
return 0;
}
|
Output :Â
125
Time Complexity: O(b)
Auxiliary Space: O(b)
Method 3 (Using bit masking)Â
we can a^n (let’s say 3^5) as 3^4 * 3^0 * 3^1 = 3^, so we can represent 5 as its binary i.e. 101
C++
#include <iostream>
using namespace std;
long long pow ( int a, int n)
{
int ans = 1;
while (n > 0)
{
int last_bit = n&1;
if (last_bit)
{
ans = ans*a;
}
a = a * a;
n = n >> 1;
}
return ans;
}
int main()
{
cout << pow (3, 5);
return 0;
}
|
Time Complexity: O(log n)
Auxiliary Space: O(1)
Last Updated :
17 Jan, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...