Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time complexity of power() [duplicate]

Tags:

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?

like image 562
Debanjan Avatar asked Mar 08 '11 10:03

Debanjan


People also ask

What is the time complexity of power function?

Time Complexity: O(N) because pow(x,n) is called recursively for each number from 1 to n.

What is the time complexity of the power function in Python?

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.

What is O n2 complexity?

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 will be the best possible time complexity of a power function x y?

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.


2 Answers

Exponentiation by Squaring.

enter image description here

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)


like image 173
Prasoon Saurav Avatar answered Sep 18 '22 15:09

Prasoon Saurav


Use Exponentiation by squaring

like image 33
Oswald Avatar answered Sep 21 '22 15:09

Oswald