Efficient Method to Calculate Power

For a^b=(a X a X a X a.....X a)

eg. for a=3, b=10
This can be written as 3^10 = (3^5)^2
Using this logic we can implement

long long power(long long a, long long b){
    long long res=1;
    while(b>0){
         if(b%2==1)//Odd Number{
             res*=a;
         }
         a*=a;
         b/=2;
    }
    return res;
}

Comments

Popular posts from this blog

Efficient method to calculate XOR series

Instagram Script to Mass Follow Unfollow in One Click