diff options
author | Yanis Zafirópulos <1265028+drkameleon@users.noreply.github.com> | 2019-11-07 18:06:48 +0100 |
---|---|---|
committer | Miran <narimiran@disroot.org> | 2019-11-07 18:06:48 +0100 |
commit | 76085e8a4523d965ebe739a9b8761ac4899279ed (patch) | |
tree | 118e783ecaf00d98559432b219231c84c743beb5 | |
parent | a2d6691af290e4500fff727136ada2b99609d896 (diff) | |
download | Nim-76085e8a4523d965ebe739a9b8761ac4899279ed.tar.gz |
added support for openArray's for `gcd` and `lcm` (#12621)
-rw-r--r-- | lib/pure/math.nim | 26 |
1 files changed, 25 insertions, 1 deletions
diff --git a/lib/pure/math.nim b/lib/pure/math.nim index 224791e5d..fcb090ca1 100644 --- a/lib/pure/math.nim +++ b/lib/pure/math.nim @@ -1062,6 +1062,19 @@ proc gcd*(x, y: SomeInteger): SomeInteger = x -= y y shl shift +proc gcd*[T](x: openArray[T]): T {.since: (1, 1).} = + ## Computes the greatest common (positive) divisor of the elements of ``x``. + ## + ## See also: + ## * `gcd proc <#gcd,T,T>`_ for integer version + runnableExamples: + doAssert gcd(@[13.5, 9.0]) == 4.5 + result = x[0] + var i = 1 + while i < x.len: + result = gcd(result, x[i]) + inc(i) + proc lcm*[T](x, y: T): T = ## Computes the least common multiple of ``x`` and ``y``. ## @@ -1072,7 +1085,18 @@ proc lcm*[T](x, y: T): T = doAssert lcm(13, 39) == 39 x div gcd(x, y) * y - +proc lcm*[T](x: openArray[T]): T {.since: (1, 1).} = + ## Computes the least common multiple of the elements of ``x``. + ## + ## See also: + ## * `gcd proc <#gcd,T,T>`_ for integer version + runnableExamples: + doAssert lcm(@[24, 30]) == 120 + result = x[0] + var i = 1 + while i < x.len: + result = lcm(result, x[i]) + inc(i) when isMainModule and not defined(JS) and not windowsCC89: # Check for no side effect annotation |