Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

conditional compilation of gcd(SomeInteger, SomeInteger) in std/math #1

Merged
merged 1 commit into from
Jun 29, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 36 additions & 34 deletions lib/pure/math.nim
Original file line number Diff line number Diff line change
Expand Up @@ -1229,40 +1229,42 @@ func gcd*[T](x, y: T): T =
swap x, y
abs x

func gcd*(x, y: SomeInteger): SomeInteger =
## Computes the greatest common (positive) divisor of `x` and `y`,
## using the binary GCD (aka Stein's) algorithm.
##
## **See also:**
## * `gcd func <#gcd,T,T>`_ for a float version
## * `lcm func <#lcm,T,T>`_
runnableExamples:
doAssert gcd(12, 8) == 4
doAssert gcd(17, 63) == 1

when x is SomeSignedInt:
var x = abs(x)
else:
var x = x
when y is SomeSignedInt:
var y = abs(y)
else:
var y = y

if x == 0:
return y
if y == 0:
return x

let shift = countTrailingZeroBits(x or y)
y = y shr countTrailingZeroBits(y)
while x != 0:
x = x shr countTrailingZeroBits(x)
if y > x:
swap y, x
x -= y
y shl shift

when usebuiltins:
## this func uses bitwise comparisons from C compilers, which are not always available.
func gcd*(x, y: SomeInteger): SomeInteger =
## Computes the greatest common (positive) divisor of `x` and `y`,
## using the binary GCD (aka Stein's) algorithm.
##
## **See also:**
## * `gcd func <#gcd,T,T>`_ for a float version
## * `lcm func <#lcm,T,T>`_
runnableExamples:
doAssert gcd(12, 8) == 4
doAssert gcd(17, 63) == 1

when x is SomeSignedInt:
var x = abs(x)
else:
var x = x
when y is SomeSignedInt:
var y = abs(y)
else:
var y = y

if x == 0:
return y
if y == 0:
return x

let shift = countTrailingZeroBits(x or y)
y = y shr countTrailingZeroBits(y)
while x != 0:
x = x shr countTrailingZeroBits(x)
if y > x:
swap y, x
x -= y
y shl shift

func gcd*[T](x: openArray[T]): T {.since: (1, 1).} =
## Computes the greatest common (positive) divisor of the elements of `x`.
##
Expand Down