Skip to content

Expand stirlings1 and stirlings2 to accept Integer #126

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

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
34 changes: 23 additions & 11 deletions src/numbers.jl
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@
"""
narayana(n,k)

Compute the Narayana number `N(n,k)` given by ``\\frac{1}{n}\\binom{n}{k}\\binom{n}{k-1}``
Compute the Narayana number `N(n,k)`` given by ``\\frac{1}{n}\\binom{n}{k}\\binom{n}{k-1}``
Wikipedia : https://en.wikipedia.org/wiki/Narayana_number
"""
function narayana(bn::Integer,bk::Integer)
Expand Down Expand Up @@ -125,19 +125,23 @@
return z[]
end

function stirlings1(n::Int, k::Int, signed::Bool=false)
stirlings1cache = Dict()

function stirlings1(n::Integer, k::Integer, signed::Bool=false)
if signed == true
return (-1)^(n - k) * stirlings1(n, k)
end

if n < 0
if haskey(stirlings1cache, Pair(n, k))
return stirlings1cache[Pair(n, k)]
elseif n < 0
throw(DomainError(n, "n must be nonnegative"))
elseif n == k == 0
return 1
return one(n)
elseif n == 0 || k == 0
return 0
return zero(n)
elseif n == k
return 1
return one(n)
elseif k == 1
return factorial(n-1)
elseif k == n - 1
Expand All @@ -148,26 +152,34 @@
return binomial(n, 2) * binomial(n, 4)
end

return (n - 1) * stirlings1(n - 1, k) + stirlings1(n - 1, k - 1)
ret = (n - 1) * stirlings1(n - 1, k) + stirlings1(n - 1, k - 1)
stirlings1cache[Pair(n, k)] = ret
return ret
end

stirlings2cache = Dict()

"""
stirlings2(n::Int, k::Int)

Compute the Stirling number of the second kind, `S(n,k)`.
"""
function stirlings2(n::Int, k::Int)
function stirlings2(n::Integer, k::Integer)
if n < 0
throw(DomainError(n, "n must be nonnegative"))
elseif haskey(stirlings2cache, Pair(n, k))
return stirlings2cache[Pair(n, k)]
elseif n == k == 0
return 1
return one(n)
elseif n == 0 || k == 0
return 0
return zero(n)
elseif k == n - 1
return binomial(n, 2)
elseif k == 2
return 2^(n-1) - 1
end

return k * stirlings2(n - 1, k) + stirlings2(n - 1, k - 1)
ret = k * stirlings2(n - 1, k) + stirlings2(n - 1, k - 1)
stirlings2cache[Pair(n, k)] = ret
ret

Check warning on line 184 in src/numbers.jl

View check run for this annotation

Codecov / codecov/patch

src/numbers.jl#L184

Added line #L184 was not covered by tests
end
Loading