Skip to content

Commit

Permalink
fix eachfactor type stability (#152)
Browse files Browse the repository at this point in the history
* fix `eachfactor` type stability

fixes #151. (test incoming)

* add test
  • Loading branch information
oscardssmith authored Feb 21, 2024
1 parent 2eb1345 commit dc67611
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 8 deletions.
4 changes: 2 additions & 2 deletions src/Primes.jl
Original file line number Diff line number Diff line change
Expand Up @@ -357,7 +357,7 @@ function iterate(f::FactorIterator{T}, state=(f.n, T(3))) where T
tz = trailing_zeros(n)
tz>0 && return (T(2), Int(tz)), (n >> tz, p)
if n <= N_SMALL_FACTORS
p = _min_factor(n)
p = T(_min_factor(n))
num_p = 1
while true
n = div(n, p)
Expand All @@ -369,7 +369,7 @@ function iterate(f::FactorIterator{T}, state=(f.n, T(3))) where T
elseif p == 3 && isprime(n)
return (n, 1), (T(1), n)
end
for p in p:2:N_SMALL_FACTORS
for p in p:T(2):T(N_SMALL_FACTORS)
_min_factor(p) == p || continue
num_p = 0
while true
Expand Down
17 changes: 11 additions & 6 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -247,11 +247,16 @@ end
@test all([issorted(collect(factor(rand(Int)))) for x in 1:100])

# test eachfactor iteration
@test iterate(eachfactor(36)) == ((2, 2), (9, 3))
@test iterate(eachfactor(7^2*5^3)) == ((5, 3), (49, 5))
@test iterate(eachfactor(257)) == ((257, 1), (1, 257))
@test iterate(eachfactor(nextprime(2^16))) == ((65537, 1), (1, 65537))

for T in (Int32, Int64, BigInt)
@test iterate(eachfactor(T(36))) == ((T(2), 2), T.((9, 3)))
@test iterate(eachfactor(T(7^2*5^3))) == ((T(5), 3), T.((49, 5)))
@test iterate(eachfactor(T(257))) == ((T(257), 1), T.((1, 257)))
@test iterate(eachfactor(T(nextprime(2^16)))) == ((T(65537), 1), T.((1, 65537)))
for (p,e) in eachfactor(T(901800900))
@test (p,e) isa Tuple{T, Int}
end
end

# Lucas-Lehmer
@test !ismersenneprime(2047)
@test ismersenneprime(8191)
Expand Down Expand Up @@ -341,7 +346,7 @@ divisors_brute_force(n) = [d for d in one(n):n if iszero(n % d)]

for n in 2:1000
ds = divisors(T(n))
@test ds == divisors(-T(n))
@test ds == divisors(-T(n))
@test sort!(ds) == divisors_brute_force(T(n))
end
end
Expand Down

0 comments on commit dc67611

Please sign in to comment.