Implement power function without using multiplication and division operators

Given two positive integers, implement 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.

 


 

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

 
Therefore, for given x = 3, we can get 3y by adding 3y-1 exactly 3 times to the result.

 
C++ implementation –
 

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).

 
C++ implementation –
 

Download   Run Code

Output: 1024

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂