From 1ad1b93f0ac27b250489591bfe1c05ae99ae495f Mon Sep 17 00:00:00 2001 From: def Date: Fri, 2 Jan 2015 21:50:57 +0100 Subject: [PATCH] Add `^`, gcd and lcm to math --- lib/pure/math.nim | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/lib/pure/math.nim b/lib/pure/math.nim index b25a1df3ab..6b1d09b901 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: "".}