Given two positive integers, implement the power function without using multiplication and division operators.

For example, for given two integers, x and y, pow(x, y) should return x raised to the power of y, i.e., xy.

Practice this problem

Method 1: Using Recursion

We know that pow(x, y) can be recursively written as:

pow(x, y) = pow(x, y – 1) * x
pow(x, 0) = 1

For example, if x = 7, we can get 7y by adding 7y-1 exactly 7 times to the result. Following is the C++, Java, and Python program that demonstrates it:

C++


Download  Run Code

Output:

343

Java


Download  Run Code

Output:

343

Python


Download  Run Code

Output:

343

Method 2

The idea is if x = ab, then log(x) = b.log(a). Since, x can be expressed as x = elog(x), by substituting the value of log(x) in the equation, we get x = eb.log(a).

Following is the C++, Java, and Python implementation of the idea:

C++


Download  Run Code

Output:

1024

Java


Download  Run Code

Output:

1024

Python


Download  Run Code

Output:

1024