0
How would you create a code that raises a number to the power of another number?
Without using ** ((thanks for the correction)) Input 1= base number Input 2= exponent ... I tried by using functions but I don't really know
5 odpowiedzi
+ 1
FYI, the power operator in python is **, not ^^.
Here is an example using the square-and-multiply method:
def myPow(n, e):
if e == 0:
return 1
if e == 1:
return n
if e % 2 == 0:
return myPow(n*n, e/2)
else:
return myPow(n*n, (e-1)/2) * n
print("Exponentiation")
n = input("Please enter the base number: ")
print(n)
e = input("Please enter the exponent: ")
print(e)
print(n + "**" + e + " = " + str(myPow(int(n), int(e))))
+ 1
If you understand the other recursion call, you should understand this one too.
Here is an example of use of the square-and-multiply method. Each line corresponds to a different level of recursion.
3**13
= ((3*3)**((13-1)/2))*3 = (9**6)*3
= ((9*9)**(6/2))*2 = (81**3)*2
= ((81*81)**((3-1)/2))*81*3 = (6561**1)*81*3 (exponent is 1, the recursion starts to bubble up)
= 6561*81*3
= 531441*3
= 1594323
Instead of doing 12 multiplications (3*3*3*...*3), we did only 5 multiplications (3*3, 9*9, 81*81, 6561*81, 531441*3). And dividing by 2 is as trivial for a computer as it is for us to divide by 10.
0
Awesome! It's really amazing to see how a short code can do that. However, I don't understand the last line of the function : return myPow(n*n, (e-1)/2) * n
0
Thank you very much!
0
print(2**3)
->8
Two * are used for raising something to the power of another.