Skip to content

Commit cbeeb85

Browse files
authored
allow primes(..., typemax(Int)) without throwing an error (#77)
1 parent ce0c1e3 commit cbeeb85

File tree

2 files changed

+12
-2
lines changed

2 files changed

+12
-2
lines changed

src/Primes.jl

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -63,9 +63,12 @@ function _primesmask(lo::Int, hi::Int)
6363
if small_sieve[i]
6464
p = wheel_prime(i)
6565
j = wheel_index(2 * div(lo - p - 1, 2p) + 1)
66-
q = p * wheel_prime(j + 1)
66+
r = widemul(p, wheel_prime(j + 1))
67+
r > m && continue # use widemul to avoid r <= m caused by overflow
6768
j = j & 7 + 1
68-
while q m
69+
q = Int(r)
70+
# q < 0 indicates overflow when incrementing q inside loop
71+
while 0 q m
6972
sieve[wheel_index(q) - wlo] = false
7073
q += wheel[j] * p
7174
j = j & 7 + 1

test/runtests.jl

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -451,3 +451,10 @@ end
451451
@test Base.IteratorEltype(prevprimes(10)) == Base.HasEltype()
452452
@test Base.IteratorSize(prevprimes(10)) == Base.SizeUnknown()
453453
end
454+
455+
@testset "primes with huge arguments" begin
456+
if Base.Sys.WORD_SIZE == 64
457+
@test primes(2^63-200, 2^63-1) == [9223372036854775643, 9223372036854775783]
458+
end
459+
@test primes(2^31-20, 2^31-1) == [2147483629, 2147483647]
460+
end

0 commit comments

Comments
 (0)