Find power of a number

Easy
0/40
Average time to solve is 15m
profile
Contributed by
75 upvotes
Asked in companies
AccentureCognizantAmazon

Problem statement

Ninja is sitting in an examination hall. He is encountered with a problem statement, "Find ‘X’ to the power ‘N’ (i.e. ‘X’ ^ ‘N’). Where ‘X’ and ‘N’ are two integers."

Ninja was not prepared for this question at all, as this question was unexpected in the exam.

He is asking for your help to solve this problem. Help Ninja to find the answer to the problem.

Note :

For this question, you can assume that 0 raised to the power of 0 is 1.
Detailed explanation ( Input/output format, Notes, Images )

Input format :

The first line of input contains integer ‘T’ denoting the number of test cases. Then each test case follows:

The first and only line of each test case contains two integers ‘X’ and ‘N’ (separated by space).

Output Format :

Output will contain a single integer which will be equal to X ^ N (i.e. X raise to the power N).

Output of each test cases will be printed on separate line.

Note:

You do not need to print anything, it has already been taken care of. Just implement the given function.

Constraints:

1 <= T <= 5
0 <= X <= 10
0 <= N <= 10

Time Limit: 1 sec.
Sample Input 1:
2
5 2
9 3
Sample Output 1:
25
729
Explanation for Sample Input 1:
Test Case 1: 
Given X = 5 and N = 2. So, 5 ^ 2 = 25. As 5 * 5 = 25.

Test Case 2:
Given X = 9 and N = 3. So, 9 ^ 3 = 729. As 9 * 9 * 9 = 729.
Sample Input 2:
2
5 0
1 10
Sample Output 2:
1
1
Hint

Think of a recursive Approach.

Approaches (2)
Recursion

The approach is to recursively call the recursive function for X and N - 1 and multiplying the value returned by the recursive function with X.

As X ^ N is same as X * (X ^ (N - 1)).

 

Approach :

 

  • First, let's say the recursive function is ‘POW(X, N)’ having ‘X’ and ‘N’ as arguments.
  • The base case for the recursive function will be for N = 0 to return the value 1. As X ^ 0 = 1 and for X = 0 to return the value 0.
  • Now call the function recursively with ‘X’ and ‘N - 1’ as arguments and return the value to the function by multiplying the value with ‘X’.
    • return X * POW(X, N - 1).
Time Complexity

O(N), where ‘N’ is the given number.

 

As, we are making recursive calls N number of times. Therefore, overall time complexity will be O(N).

Space Complexity

O(1)

 

As we are using constant space. Therefore, time complexity will be O(1).

Code Solution
(100% EXP penalty)
Find power of a number
Full screen
Console