diff options
author | Miran <narimiran@disroot.org> | 2019-05-21 15:57:33 +0200 |
---|---|---|
committer | GitHub <noreply@github.com> | 2019-05-21 15:57:33 +0200 |
commit | 9bd4347abb0da93f2c3cf55686f1f997428261cc (patch) | |
tree | 6a3cdd7719e84ae1bb2ede570a158cadb7fbbec1 /lib/pure | |
parent | 658651651124fb47f7ce721882528e7e4eed2452 (diff) | |
download | Nim-9bd4347abb0da93f2c3cf55686f1f997428261cc.tar.gz |
fix #10910, optimize squaring and cubing (#11291)
Diffstat (limited to 'lib/pure')
-rw-r--r-- | lib/pure/math.nim | 37 |
1 files changed, 21 insertions, 16 deletions
diff --git a/lib/pure/math.nim b/lib/pure/math.nim index 05d562182..442c45ead 100644 --- a/lib/pure/math.nim +++ b/lib/pure/math.nim @@ -975,23 +975,28 @@ proc `^`*[T](x: T, y: Natural): T = ## * `sqrt proc <#sqrt,float64>`_ ## * `cbrt proc <#cbrt,float64>`_ ## - ## .. code-block:: nim - ## echo 2^3 # 8 - ## echo -2^3 # -8 - when compiles(y >= T(0)): - assert y >= T(0) + runnableExamples: + assert -3.0^0 == 1.0 + assert -3^1 == -3 + assert -3^2 == 9 + assert -3.0^3 == -27.0 + assert -3.0^4 == 81.0 + + case y + of 0: result = 1 + of 1: result = x + of 2: result = x * x + of 3: result = x * x * x else: - assert T(y) >= T(0) - 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 + 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 = ## Computes the greatest common (positive) divisor of ``x`` and ``y``. |