Fix exponentiation operation to avoid overflow.
The exponentation implementation unnecessarily multiplied the result with itself at the end if the exponent was an even number. This led to overflow if result*result > high(int).
This commit is contained in:
parent
134c44f3be
commit
22789a8275
1 changed files with 3 additions and 1 deletions
|
|
@ -427,10 +427,12 @@ proc `^`*[T](x, y: T): T =
|
||||||
var (x, y) = (x, y)
|
var (x, y) = (x, y)
|
||||||
result = 1
|
result = 1
|
||||||
|
|
||||||
while y != 0:
|
while true:
|
||||||
if (y and 1) != 0:
|
if (y and 1) != 0:
|
||||||
result *= x
|
result *= x
|
||||||
y = y shr 1
|
y = y shr 1
|
||||||
|
if y == 0:
|
||||||
|
break
|
||||||
x *= x
|
x *= x
|
||||||
|
|
||||||
proc gcd*[T](x, y: T): T =
|
proc gcd*[T](x, y: T): T =
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue