Add ^, gcd and lcm to math

This commit is contained in:
def
2015-01-02 21:50:57 +01:00
parent 553b9308b7
commit 1ad1b93f0a

View File

@@ -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>".}