VOOZH about

URL: https://www.geeksforgeeks.org/dsa/write-you-own-power-without-using-multiplication-and-division/

⇱ Write you own Power without using multiplication(*) and division(/) operators - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Write you own Power without using multiplication(*) and division(/) operators

Last Updated : 23 Jul, 2025

Method 1 (Using Nested Loops): We can calculate power by using repeated addition. For example to calculate 5^6. 

1) First 5 times add 5, we get 25. (5^2) 
2) Then 5 times add 25, we get 125. (5^3) 
3) Then 5 times add 125, we get 625 (5^4) 
4) Then 5 times add 625, we get 3125 (5^5) 
5) Then 5 times add 3125, we get 15625 (5^6) 

Output : 

125

Time Complexity: O(a * b)

Auxiliary Space: O(1)

Method 2 (Using Recursion): Recursively add a to get the multiplication of two numbers. And recursively multiply to get a raise to the power b.

Output : 

125

Time Complexity: O(b)

Auxiliary Space: O(b)

Method 3 (Using bit masking) 

Approach: We can a^n (let's say 3^5) as 3^4 * 3^0 * 3^1 = 3^5, so we can represent 5 as its binary i.e. 101

Time Complexity: O(log n)

Auxiliary Space: O(1)

Please write comments if you find any bug in the above code/algorithm, or find other ways to solve the same problem.

Method 4 (Using Exponentiation by Squaring): 


This method is based on the idea that the result of a^b can be obtained by dividing the problem into smaller sub-problems of size b/2 and solving them recursively.

Algorithm:

  1. If b==0, return 1.
  2. If b is even, return pow(a*a, b/2).
  3. If b is odd, return apow(aa, (b-1)/2).

Output
125

Time complexity of the above pow function is O(log b) because the function is dividing the problem into half in each recursive call.

The auxiliary space or space complexity of the function is also O(log b) because the maximum number of recursive calls will be equal to the log base 2 of the input value b.

Comment
Article Tags: