Given two integers A and N, the task is to calculate A raised to power N (i.e. AN).
Input: A = 3, N = 5
3 raised to power 5 = (3*3*3*3*3) = 243
Input: A = 21, N = 4
21 raised to power 4 = (21*21*21*21) = 194481
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)
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:
Time Complexity: O(logN)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Winner in the Rock-Paper-Scissor game using Bit manipulation
- Bit manipulation | Swap Endianness of a number
- Maximize the Expression | Bit Manipulation
- Maximize the expression (A AND X) * (B AND X) | Bit Manipulation
- Bits manipulation (Important tactics)
- Fast method to calculate inverse square root of a floating point number in IEEE 754 format
- Exponential Squaring (Fast Modulo Multiplication)
- Fast average of two numbers without division
- Fast inverse square root
- How does Floyd's slow and fast pointers approach work?
- Fast Fourier Transformation for poynomial multiplication
- Inserting m into n such that m starts at bit j and ends at bit i.
- Inserting M into N such that m starts at bit j and ends at bit i | Set-2
- Minimum bit flips such that every K consecutive bits contain at least one set bit
- Find Duplicates of array using bit array
- Josephus Problem Using Bit Magic
- Check if a number is positive, negative or zero using bit operators
- Space optimization using bit manipulations
- Find letter's position in Alphabet using Bit operation
- Find average of two numbers using bit operation
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.