Skip to content

Commit

Permalink
make gcd and lcm positive (fix JuliaLang#4810)
Browse files Browse the repository at this point in the history
  • Loading branch information
stevengj committed Nov 14, 2013
1 parent 2b442d5 commit db6d2e0
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 8 deletions.
11 changes: 4 additions & 7 deletions base/intfuncs.jl
Original file line number Diff line number Diff line change
Expand Up @@ -33,16 +33,14 @@ abs(x::Signed) = flipsign(x,x)
## number-theoretic functions ##

function gcd{T<:Integer}(a::T, b::T)
neg = a < 0
while b != 0
t = b
b = rem(a, b)
a = t
end
g = abs(a)
neg ? -g : g
abs(a)
end
lcm{T<:Integer}(a::T, b::T) = a * div(b, gcd(b,a))
lcm{T<:Integer}(a::T, b::T) = abs(a * div(b, gcd(b,a)))

gcd(a::Integer) = a
lcm(a::Integer) = a
Expand All @@ -61,15 +59,14 @@ function gcdx{T<:Integer}(a::T, b::T)
s0, s1 = s1, s0 - q*s1
t0, t1 = t1, t0 - q*t1
end
(a, s0, t0)
a < 0 ? (-a, -s0, -t0) : (a, s0, t0)
end
gcdx(a::Integer, b::Integer) = gcdx(promote(a,b)...)

# multiplicative inverse of n mod m, error if none
function invmod(n, m)
g, x, y = gcdx(n, m)
g == 1 ? (x < 0 ? m + x : x) :
g == -1 ? (x > 0 ? abs(m) - x : -x) : error("no inverse exists")
g == 1 ? (x < 0 ? abs(m) + x : x) : error("no inverse exists")
end

# ^ for any x supporting *
Expand Down
2 changes: 1 addition & 1 deletion base/rational.jl
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ immutable Rational{T<:Integer} <: Real
if num == 0 && den == 0
error("invalid rational: 0//0")
end
g = gcd(den, num)
g = den < 0 ? -gcd(den,num) : gcd(den, num)
new(div(num, g), div(den, g))
end
end
Expand Down

0 comments on commit db6d2e0

Please sign in to comment.