Sunday 10 September 2017

Implementing your own power function

How many of you have used that pow(a,b) function in your codes? Well, I think most of you would have used it be it in C/C++/Java/Python or any other programing language which provide this inbuilt function in their libraries.
Ever wondered how that function works? or what is the time complexity in which it evaluates a^b ? What if you are asked to evaluate this on your own? What comes to your mind? The basic O(n) complexity solution? i.e multiplying a*a*a*a........ n times to compute? Can you think of a better approach having a time complexity of Olog(n)?
Yes, you can guess that if you are asked to do this in time complexity of O(log(n)) then we may end up applying the binary search. How? Let's see :

It is similar to a basic Divide and Conquer approach i.e dividing the problems into subparts and then solving it using the base case.
Suppose you have to find the value of 13^24.
 You can proceed in this way:
 13^24 = (13^12 )* (13^12)
 13^12 = (13^6)*(13^6)
 13^6 = (13^3)*(13^3)
 13^3 = (13^1) * (13^1) * 13 :-> as 3/2 = 1 (integer division )
 13^1 = (13^0)*(13^0) * 13
 What did you observe?
 if we have to compute a^n and if n is even we have to recursively compute a^(n/2) once and square it  and if n is odd we have to compute the square of  a^(n/2) and multiply it with a
 Therefore we are reducing the search space or say computing space by half which gives us the time complexity of O(log(n)).

int pow(int a, int n)
{
    if(n==0)
   {
      return 1;  //base condition
   }
   int temp = pow(a,n/2);
   if(n%2==0)
   {
       int ans = temp*temp;
      return ans;
   }
   else 
   {
      return (a*temp*temp);
   }
}



No comments:

Post a Comment