I implemented this function power()
which takes two arguments a
and b
and computes ab.
typedef long long int LL;
LL power(int a,int b)
{
int i = 1;
LL pow = 1;
for( ; i <= b ; ++i )
pow *= a;
return pow;
}
Given : ab falls in the range of long long int
.
Problem : How to reduce the time complexity of my algorithm?
Time Complexity: O(N) because pow(x,n) is called recursively for each number from 1 to n.
math. pow() function can also calculate the exponential value in Python. The math. pow() shows the time complexity of O(1) due to the floating-point exponentiation, which is better than the built-in pow() function, But due to this, it sacrifices the precision of the result.
O(n2) O(n2) represents a function whose complexity is directly proportional to the square of the input size. Adding more nested iterations through the input will increase the complexity which could then represent O(n3) with 3 total iterations and O(n4) with 4 total iterations.
What can be the best possible time complexity of your power function? Explanation: We can calculate power using divide and conquer in O(Logn) time.
Exponentiation by Squaring.
A non-recursive implementation
LL power(int a, int b)
{
LL pow = 1;
while ( b )
{
if ( b & 1 )
{
pow = pow * a;
--b;
}
a = a*a;
b = b/2;
}
return pow;
}
This algorithm requires log2b squarings and at most log2b multiplications.
The running time is O(log b)
Use Exponentiation by squaring
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With