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

 
1 Star2 Stars3 Stars4 Stars5 Stars (3 votes, average: 5.00 out of 5)

Loading...

Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
newest oldest most voted
Notify of
权杨
Guest

方法2 应该是ln(x)而不是log(x)吧