Skip to content

Commit

Permalink
Better sizehint for primes
Browse files Browse the repository at this point in the history
  • Loading branch information
mschauer committed May 13, 2016
1 parent 9c2a233 commit 8a5d887
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 2 deletions.
5 changes: 3 additions & 2 deletions base/primes.jl
Original file line number Diff line number Diff line change
Expand Up @@ -78,12 +78,13 @@ primesmask(n::Integer) = n <= typemax(Int) ? primesmask(Int(n)) :

function primes(lo::Int, hi::Int)
lo hi || throw(ArgumentError("the condition lo ≤ hi must be met"))
lo = max(2, lo) # note: if now lo > hi, then hi < 7
list = Int[]
lo 2 hi && push!(list, 2)
lo 3 hi && push!(list, 3)
lo 5 hi && push!(list, 5)
hi < 7 && return list
sizehint!(list, floor(Int, hi / log(hi)))
hi < 7 && return list
sizehint!(list, floor(Int, hi / log(hi) - lo / log(lo)))
sieve = _primesmask(max(7, lo), hi)
lwi = wheel_index(lo - 1)
@inbounds for i = 1:length(sieve) # don't use eachindex here
Expand Down
3 changes: 3 additions & 0 deletions test/numbers.jl
Original file line number Diff line number Diff line change
Expand Up @@ -2253,6 +2253,9 @@ for T in [Int,BigInt], n = [1:1000;1000000]
@test s[k] == primesmask(k, k)[1]
end
end
let i = rand(1:2^(3*min(WORD_SIZE,64)÷4))
@test primes(i,i+1476) == filter(isprime, i:i + 1476) == filter(isprime, big(i:i + 1476))
end

@test !isprime(1000000003)
@test !isprime(1000000005)
Expand Down

0 comments on commit 8a5d887

Please sign in to comment.