Skip to content

Commit

Permalink
Added arg-too-big checks for primorial & fibonacci (#1732)
Browse files Browse the repository at this point in the history
  • Loading branch information
JohnAAbbott committed Apr 26, 2024
1 parent 8a25bea commit 09c3bef
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 0 deletions.
8 changes: 8 additions & 0 deletions src/flint/fmpz.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1831,6 +1831,10 @@ equal to $x$. If $x < 0$ we throw a `DomainError()`.
"""
function primorial(x::Int)
x < 0 && throw(DomainError(x, "Argument must be non-negative"))
# Up to 28 is OK for Int32, up to 52 is OK for Int64, up to 100 is OK for Int128; beyond is too large
if (Int == Int32 && x > 28) || (Int == Int64 && x > 52) || (Int == Int128 && x > 100)
throw(OverflowError("primorial(::Int)"))
end
z = ZZRingElem()
ccall((:fmpz_primorial, libflint), Nothing,
(Ref{ZZRingElem}, UInt), z, UInt(x))
Expand Down Expand Up @@ -1858,6 +1862,10 @@ Return the $x$-th Fibonacci number $F_x$. We define $F_1 = 1$, $F_2 = 1$ and
$F_{i + 1} = F_i + F_{i - 1}$ for all integers $i$.
"""
function fibonacci(x::Int)
# Up to 46 is OK for Int32; up to 92 is OK for Int64; up to 184 is OK for Int128; beyond is too large
if (Int == Int32 && abs(x) > 46) || (Int == Int64 && abs(x) > 92) || (Int == Int128 && abs(x) > 184)
throw(OverflowError("fibonacci(::Int)"))
end
z = ZZRingElem()
ccall((:fmpz_fib_ui, libflint), Nothing,
(Ref{ZZRingElem}, UInt), z, UInt(abs(x)))
Expand Down
4 changes: 4 additions & 0 deletions test/flint/fmpz-test.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1070,6 +1070,8 @@ end

@test fibonacci(ZZRingElem(-2)) == -1

@test_throws OverflowError fibonacci(999)

@test_throws DomainError euler_phi(-ZZRingElem(12480))

@test remove(ZZRingElem(12), ZZRingElem(2)) == (2, 3)
Expand Down Expand Up @@ -1118,6 +1120,8 @@ end

@test primorial(7) == 210

@test_throws OverflowError primorial(999)

@test_throws DomainError primorial(-7)

for a in [-ZZ(3)^100, ZZ(3)^100]
Expand Down

0 comments on commit 09c3bef

Please sign in to comment.