Skip to content

Commit c5a17f9

Browse files
authored
Merge pull request #74 from JuliaMath/bell
Corrected and optimized bellnum
2 parents 27b9d2c + b774f03 commit c5a17f9

File tree

2 files changed

+26
-13
lines changed

2 files changed

+26
-13
lines changed

src/numbers.jl

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -15,24 +15,24 @@ export bellnum,
1515
1616
Compute the ``n``th Bell number.
1717
"""
18-
function bellnum(bn::Integer)
19-
if bn < 0
20-
throw(DomainError(bn, "n must be nonnegative"))
21-
else
22-
n = BigInt(bn)
18+
function bellnum(n::Integer)
19+
if n < 0
20+
throw(DomainError(n))
21+
elseif n < 2
22+
return 1
2323
end
24-
list = Vector{BigInt}(undef, div(n*(n+1), 2))
24+
list = Vector{BigInt}(undef, n)
2525
list[1] = 1
2626
for i = 2:n
27-
beg = div(i*(i-1),2)
28-
list[beg+1] = list[beg]
29-
for j = 2:i
30-
list[beg+j] = list[beg+j-1]+list[beg+j-i]
27+
for j = 1:i - 2
28+
list[i - j - 1] += list[i - j]
3129
end
30+
list[i] = list[1] + list[i - 1]
3231
end
33-
return list[end]
32+
return list[n]
3433
end
3534

35+
3636
"""
3737
catalannum(n)
3838

test/numbers.jl

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,19 @@
5656
@test stirlings2(6, 6) == 1
5757

5858
# bell
59-
@test bellnum(7) == 877
59+
@test bellnum.(0:10) == [
60+
1
61+
1
62+
2
63+
5
64+
15
65+
52
66+
203
67+
877
68+
4140
69+
21147
70+
115975
71+
]
72+
6073
@test bellnum(42) == parse(BigInt,"35742549198872617291353508656626642567")
61-
@test_throws DomainError bellnum(-1)
74+
@test_throws DomainError(-1) bellnum(-1)

0 commit comments

Comments
 (0)