Fast Exponention using Bit Manipulation - GeeksforGeeks

17 Jul, 2021
Given two integers A and N, the task is to calculate A raised to power N (i.e. AN).
Examples: 
Input: A = 3, N = 5 Output: 243 Explanation: 3 raised to power 5 = (3*3*3*3*3) = 243
Input: A = 21, N = 4Output: 194481 Explanation: 21 raised to power 4 = (21*21*21*21) = 194481  
Naive Approach: The simplest approach to solve this problem is to repetitively multiply A, N times and print the product. 
Time Complexity: O(N) Auxiliary Space: O(1)
Efficient Approach: To optimize the above approach, the idea is to use Bit Manipulation. Convert the integer N to its binary form and follow the steps below:  
Initialize ans to store the final answer of AN.
Traverse until N > 0 and in each iteration, perform Right Shift operation on it.
Also, in each iteration, multiply A with itself and update it.
If current LSB is set, then multiply current value of A to ans.
Finally, after completing the above steps, print ans.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ Program to implement// the above approach#include <iostream>using namespace std; // Function to return a^nint powerOptimised(int a, int n){     // Stores final answer    int ans = 1;     while (n > 0) {         int last_bit = (n & 1);         // Check if current LSB        // is set        if (last_bit) {            ans = ans * a;        }         a = a * a;         // Right shift        n = n >> 1;    }     return ans;} // Driver Codeint main(){    int a = 3, n = 5;     cout << powerOptimised(a, n);     return 0;}
// Java program to implement// the above approachclass GFG{ // Function to return a^nstatic int powerOptimised(int a, int n){     // Stores final answer    int ans = 1;     while (n > 0)    {        int last_bit = (n & 1);         // Check if current LSB        // is set        if (last_bit > 0)        {            ans = ans * a;        }                 a = a * a;         // Right shift        n = n >> 1;    }    return ans;} // Driver Codepublic static void main(String[] args){    int a = 3, n = 5;     System.out.print(powerOptimised(a, n));}} // This code is contributed by PrinciRaj1992
# Python3 program to implement# the above approach # Function to return a^ndef powerOptimised(a, n):         # Stores final answer    ans = 1         while (n > 0):        last_bit = (n & 1)                 # Check if current LSB        # is set        if (last_bit):            ans = ans * a        a = a * a                 # Right shift        n = n >> 1             return ans # Driver codeif __name__ == '__main__':         a = 3    n = 5         print(powerOptimised(a,n)) # This code is contributed by virusbuddah_
// C# program to implement// the above approachusing System; class GFG{ // Function to return a^nstatic int powerOptimised(int a, int n){         // Stores readonly answer    int ans = 1;     while (n > 0)    {        int last_bit = (n & 1);         // Check if current LSB        // is set        if (last_bit > 0)        {            ans = ans * a;        }        a = a * a;         // Right shift        n = n >> 1;    }    return ans;} // Driver Codepublic static void Main(String[] args){    int a = 3, n = 5;     Console.Write(powerOptimised(a, n));}} // This code is contributed by Princi Singh
<script> // Javascript program to implement// the above approach // Function to return a^nfunction powerOptimised(a, n){       // Stores final answer    let ans = 1;       while (n > 0)    {        let last_bit = (n & 1);           // Check if current LSB        // is set        if (last_bit > 0)        {            ans = ans * a;        }                   a = a * a;           // Right shift        n = n >> 1;    }    return ans;}      // Driver Code             let a = 3, n = 5;       document.write(powerOptimised(a, n));       </script>
243
 
Time Complexity: O(logN) Auxiliary Space: O(1) 
virusbuddha
princiraj1992
princi singh
chinmoy1997pal
saurabh1990aror
Bitwise-AND
maths-power
Bit Magic
Mathematical
Mathematical
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Set, Clear and Toggle a given bit of a number in C
Program to find parity
Write an Efficient Method to Check if a Number is Multiple of 3
Check whether K-th bit is set or not
Hamming code Implementation in C/C++
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Program to find GCD or HCF of two numbers