Skip to content

Commit ce0c1e3

Browse files
authored
Fix prevprime for unsigned integers (#75)
1 parent 187ec9e commit ce0c1e3

File tree

2 files changed

+8
-2
lines changed

2 files changed

+8
-2
lines changed

src/Primes.jl

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -533,6 +533,8 @@ end
533533

534534
add(n::BigInt, x::Int) = n + x
535535
add(n::Integer, x::Int) = Base.checked_add(n, oftype(n, x))
536+
sub(n::BigInt, x::Int) = n - x
537+
sub(n::Integer, x::Int) = Base.checked_sub(n, oftype(n, x))
536538

537539
# add_! : "may" mutate the Integer argument (only for BigInt currently)
538540

@@ -548,6 +550,8 @@ end
548550

549551
# checked addition, without mutation
550552
add_!(n::Integer, x::Int) = add(n, x)
553+
sub_!(n::BigInt, x::Int) = add_!(n, -x)
554+
sub_!(n::Integer, x::Int) = sub(n, x)
551555

552556
"""
553557
nextprime(n::Integer, i::Integer=1; interval::Integer=1)
@@ -662,9 +666,9 @@ function prevprime(n::Integer, i::Integer=1; interval::Integer=1)
662666

663667
# A bit ugly, but this lets us skip half of the isprime tests when isodd(interval)
664668
@inline function decrement(n)
665-
n = add_!(n, -interval)
669+
n = sub_!(n, interval)
666670
iseven(n) && n != 2 ? # n obviously not prime
667-
add_!(n, -interval) :
671+
sub_!(n, interval) :
668672
n
669673
end
670674

test/runtests.jl

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -360,6 +360,8 @@ end
360360
@test prevprime(3) == 3
361361
@test prevprime(3, 2) == 2
362362
@test prevprime(2) == 2
363+
@test prevprime(typemax(UInt8)) == prevprime(big(typemax(UInt8)))
364+
@test typeof(prevprime(typemax(UInt8))) === UInt8
363365
@test_throws ArgumentError prevprime(2, 2)
364366

365367
@test_throws DomainError prevprime(rand(-100:100), 0)

0 commit comments

Comments
 (0)