diff options
author | def <dennis@felsin9.de> | 2015-01-02 21:50:57 +0100 |
---|---|---|
committer | def <dennis@felsin9.de> | 2015-02-16 20:43:20 +0100 |
commit | 1ad1b93f0ac27b250489591bfe1c05ae99ae495f (patch) | |
tree | 2b5203bea443a08d07bfe3a1a3ac70242557374b | |
parent | 553b9308b7b4e050dca01f6fb4b032a405248310 (diff) | |
download | Nim-1ad1b93f0ac27b250489591bfe1c05ae99ae495f.tar.gz |
Add `^`, gcd and lcm to math
-rw-r--r-- | lib/pure/math.nim | 24 |
1 files changed, 24 insertions, 0 deletions
diff --git a/lib/pure/math.nim b/lib/pure/math.nim index b25a1df3a..6b1d09b90 100644 --- a/lib/pure/math.nim +++ b/lib/pure/math.nim @@ -329,6 +329,30 @@ proc standardDeviation*(s: RunningStat): float = {.pop.} {.pop.} +proc `^`*[T](x, y: T): T = + ## Computes ``x`` to the power ``y`. ``x`` must be non-negative, use + ## `pow <#pow,float,float>` for negative exponents. + assert y >= 0 + var (x, y) = (x, y) + result = 1 + + while y != 0: + if (y and 1) != 0: + result *= x + y = y shr 1 + x *= x + +proc gcd*[T](x, y: T): T = + ## Computes the greatest common divisor of ``x`` and ``y``. + if y != 0: + gcd(y, x mod y) + else: + x.abs + +proc lcm*[T](x, y: T): T = + ## Computes the least common multiple of ``x`` and ``y``. + x div gcd(x, y) * y + when isMainModule and not defined(JS): proc gettime(dummy: ptr cint): cint {.importc: "time", header: "<time.h>".} |