Algorithm to calculate power(k,n).

Objective:  Given two numbers ‘k’ and ‘n’. Write an algorithm to calculate kn.

k = 4, n = 5
kn = 45 = 1024

k = 2, n = 3
kn = 23 = 8


Method 1: Brute Force

Use for loop to iterate from 1 to n and do k*k for each iteration.

Time Complexity: O(n)


Method 2: Only if ‘k’ and ‘n’ are positive.

1.     Use recursion.

2.     Divide the problem into sub problems with size n/2 and solve it recursively.

3.     Handle the case if n is odd. Multiply the final result with k.

Time Complexity: O(logn)


24 = 22 * 22 = 4*4 = 16.
So instead of doing it 2*2*2*2, we have divided into two parts = 22 * 22


Method 3: Handle the case if n is negative

1.     Same as Method 2 above.

2.     Instead of multiplying with k, divide with k.

3.     See the code for more understanding.

Time Complexity: O(logn)



4 power -2 :  Result: 0.0625

Top Companies Interview Questions..-


If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: