Make gcd iterative instead of recursive
This commit is contained in:
parent
cc757d538c
commit
43bc72f1fe
1 changed files with 5 additions and 4 deletions
|
|
@ -344,10 +344,11 @@ proc `^`*[T](x, y: T): T =
|
||||||
|
|
||||||
proc gcd*[T](x, y: T): T =
|
proc gcd*[T](x, y: T): T =
|
||||||
## Computes the greatest common divisor of ``x`` and ``y``.
|
## Computes the greatest common divisor of ``x`` and ``y``.
|
||||||
if y != 0:
|
var (x,y) = (x,y)
|
||||||
gcd(y, x mod y)
|
while y != 0:
|
||||||
else:
|
x = x mod y
|
||||||
x.abs
|
swap x, y
|
||||||
|
abs x
|
||||||
|
|
||||||
proc lcm*[T](x, y: T): T =
|
proc lcm*[T](x, y: T): T =
|
||||||
## Computes the least common multiple of ``x`` and ``y``.
|
## Computes the least common multiple of ``x`` and ``y``.
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue