fix #10910, optimize squaring and cubing (#11291)

This commit is contained in:
Miran 2019-05-21 15:57:33 +02:00 • committed by GitHub
commit 9bd4347abb
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -975,23 +975,28 @@ proc `^`*[T](x: T, y: Natural): T =
## * `sqrt proc <#sqrt,float64>`_ ## * `sqrt proc <#sqrt,float64>`_
## * `cbrt proc <#cbrt,float64>`_ ## * `cbrt proc <#cbrt,float64>`_
## ##
## .. code-block:: nim runnableExamples:
## echo 2^3 # 8 assert -3.0^0 == 1.0
## echo -2^3 # -8 assert -3^1 == -3
when compiles(y >= T(0)): assert -3^2 == 9
assert y >= T(0) assert -3.0^3 == -27.0
else: assert -3.0^4 == 81.0
assert T(y) >= T(0)
var (x, y) = (x, y)
result = 1
while true: case y
if (y and 1) != 0: of 0: result = 1
result *= x of 1: result = x
y = y shr 1 of 2: result = x * x
if y == 0: of 3: result = x * x * x
break else:
x *= x var (x, y) = (x, y)
result = 1
while true:
if (y and 1) != 0:
result *= x
y = y shr 1
if y == 0:
break
x *= x
proc gcd*[T](x, y: T): T = proc gcd*[T](x, y: T): T =
## Computes the greatest common (positive) divisor of ``x`` and ``y``. ## Computes the greatest common (positive) divisor of ``x`` and ``y``.