n004rp
n004rp

Reputation: 45

OverflowError: int too large to convert to float even with "Decimal" - Python

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]

1

Upvotes: 2

Views: 153

Answers (1)

md2perpe
md2perpe

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

Related Questions