Reputation: 45
This question got already an answer on stackoverflow and the recommended solution was to use "Decimal" form the module math
But Decimal didn't work ->
from decimal import Decimal
import math
def pow_opt(x:int, n:int)-> int:
result = 1
while Decimal(math.pow(x,n)):
if (n%2 == 0):
x = x**2
n = n/2
else:
result = result*x
n = n-1
print(pow_opt(4,2))
And the following error is returned :
[click to see error]
Upvotes: 2
Views: 153
Reputation: 3081
You hardly need any Decimal
for that. Your implementation is incorrect. When it has been corrected (see code below) it works with integers:
def pow_opt(x:int, n:int)-> int:
result = 1
while n:
if (n%2 == 0):
x = x**2
n = n/2
else:
result = result*x
n = n-1
return result
Upvotes: 2