mirror of
https://github.com/nim-lang/Nim.git
synced 2026-07-19 15:31:28 +00:00
Add ^, gcd and lcm to math
This commit is contained in:
@@ -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>".}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user