Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve performance of derangement/subfactorial with iterative implementation #146

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 17 additions & 3 deletions src/factorials.jl
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,23 @@
Compute the number of permutations of `n` with no fixed points, also known as the
subfactorial. An alias `subfactorial` for this function is provided for convenience.
"""
function derangement(sn::Integer)
n = BigInt(sn)
return numerator(factorial(n) * sum([(-1)^k // factorial(k) for k = 0:n]))
function derangement(n::Integer)
if n < 0
throw(DomainError(n, "n must be nonnegative"))
elseif n <= 1
return BigInt(1-n)

Check warning on line 45 in src/factorials.jl

View check run for this annotation

Codecov / codecov/patch

src/factorials.jl#L45

Added line #L45 was not covered by tests
end
d = BigInt(0)
for i in 2:n
# d = i * d + (iseven(i) ? 1 : -1)
Base.GMP.MPZ.mul_ui!(d, i)
if iseven(i)
Base.GMP.MPZ.add_ui!(d, 1)
else
Base.GMP.MPZ.sub_ui!(d, 1)
end
end
return d
end
const subfactorial = derangement

Expand Down
1 change: 1 addition & 0 deletions test/factorials.jl
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
# derangement
@test derangement(4) == subfactorial(4) == 9
@test derangement(24) == parse(BigInt, "228250211305338670494289")
@test_throws DomainError derangement(-1)

# partialderangement
@test partialderangement(7, 3) == 315
Expand Down
Loading