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 =
|
||||
## Computes the greatest common divisor of ``x`` and ``y``.
|
||||
if y != 0:
|
||||
gcd(y, x mod y)
|
||||
else:
|
||||
x.abs
|
||||
var (x,y) = (x,y)
|
||||
while y != 0:
|
||||
x = x mod y
|
||||
swap x, y
|
||||
abs x
|
||||
|
||||
proc lcm*[T](x, y: T): T =
|
||||
## Computes the least common multiple of ``x`` and ``y``.
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue