written in python, but the logic would be the same:
Code
def mypowerfunction(number, power):
number_of_multiplications = 0
exponent_counter = 0
block = number*number*number
number_of_multiplications += 2
solution = 1
while (exponent_counter + 3) <= power:
solution=block*solution
number_of_multiplications +=1
exponent_counter +=3
while exponent_counter < power:
solution = solution * number
exponent_counter +=1
number_of_multiplications +=1
return solution, number_of_multiplications
print mypowerfunction(2,21)
Quote (output)
(2097152, 9)
So that took 9 multiplication operations (of course it inserted some while loops).
if this is a serious project, you should add a check to ensure the the power input is >= 0, that the power input is an integer, that the "number" input is a number, and that that both inputs do not equal 0 at the same time (0^0 is undefined).
This post was edited by Azrad on Sep 5 2013 11:17am