Skip to content

Commit 1a69cfe

Browse files
author
Arda Aytekin
committed
Fix Euclid's algorithm in gcd
Fixes #122.
1 parent afce991 commit 1a69cfe

File tree

2 files changed

+26
-4
lines changed

2 files changed

+26
-4
lines changed

src/Polynomials.jl

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -665,11 +665,19 @@ Poly(4.0 - 6.0⋅x + 2.0⋅x^2)
665665
```
666666
"""
667667
function gcd{T, S}(a::Poly{T}, b::Poly{S})
668-
R = typeof(one(T)/one(S))
669-
degree(b) == 0 && b zero(b) && return convert(Poly{R}, a)
668+
U = typeof(one(T)/one(S))
669+
r₀, r₁ = convert(Poly{U}, a), truncate(convert(Poly{U}, b))
670+
iter = 1
671+
itermax = degree(b) + 1
672+
673+
while r₁ zero(r₁) && iter itermax # just to avoid unnecessary recursion
674+
_, rtemp = divrem(r₀, r₁)
675+
r₀ = r₁
676+
r₁ = truncate(rtemp)
677+
iter += 1
678+
end
670679

671-
s, r = divrem(a, b)
672-
return gcd(b, r)
680+
return r₀
673681
end
674682

675683

test/runtests.jl

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -345,3 +345,17 @@ end
345345
@test length(collect(p1)) == degree(p1)+1
346346

347347
@test [p1[idx] for idx in eachindex(p1)] == [1,2,0,3]
348+
349+
p1 = Poly([2.,5.,1.])
350+
p2 = Poly([1.,2.,3.])
351+
352+
@test degree(gcd(p1, p2)) == 0 # no common roots
353+
@test degree(gcd(p1, Poly(5))) == 0 # ditto
354+
@test degree(gcd(p1, Poly(eps(0.)))) == 0 # ditto
355+
@test degree(gcd(p1, Poly(0))) == degree(p1) # Poly(0) has the roots of p1
356+
@test degree(gcd(p1+p2*170.10734737144486, p2)) == 0 # see, c.f., #122
357+
358+
p1 = poly([1.,2.,3.])
359+
p2 = poly([1.,2.,6.])
360+
361+
@test (res = roots(gcd(p1, p2)); 1. res && 2. res)

0 commit comments

Comments
 (0)