Skip to content

Commit 2bd33e6

Browse files
authored
Add Aliquot sum (#18)
1 parent 90b32ed commit 2bd33e6

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

.spec/math/aliquot_sum_spec.lua

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
describe("Aliquot sum", function()
2+
local aliquot_sum = require("math.aliquot_sum")
3+
4+
it("should handle general cases", function()
5+
assert.equal(0, aliquot_sum(1))
6+
assert.equal(1, aliquot_sum(2))
7+
assert.equal(1, aliquot_sum(3))
8+
assert.equal(1 + 2, aliquot_sum(4))
9+
assert.equal(1, aliquot_sum(5))
10+
assert.equal(1 + 2 + 3, aliquot_sum(6))
11+
assert.equal(1, aliquot_sum(7))
12+
assert.equal(1 + 2 + 4, aliquot_sum(8))
13+
assert.equal(1 + 3, aliquot_sum(9))
14+
assert.equal(106, aliquot_sum(80))
15+
assert.equal(114, aliquot_sum(102))
16+
assert.equal(312, aliquot_sum(168))
17+
assert.equal(14, aliquot_sum(169))
18+
assert.equal(154, aliquot_sum(170))
19+
assert.equal(89, aliquot_sum(171))
20+
assert.equal(533, aliquot_sum(1771))
21+
assert.equal(7044, aliquot_sum(7852))
22+
end)
23+
24+
it("should throw error when input is 0", function()
25+
assert.has_error(function()
26+
aliquot_sum(0)
27+
end)
28+
end)
29+
30+
it("should throw error when input is negative", function()
31+
assert.has_error(function()
32+
aliquot_sum(-1)
33+
end)
34+
end)
35+
end)

src/math/aliquot_sum.lua

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
-- Computes the sum of proper divisors
2+
-- of the input number of n, i.e.
3+
-- sum of divisors of n that are less than n.
4+
return function(n)
5+
assert(n > 0, "input must be positive")
6+
if n == 1 then
7+
return 0
8+
end
9+
local res = 1
10+
for i = 2, math.sqrt(n) do
11+
if n % i == 0 then
12+
res = res + i
13+
local complement = n / i
14+
-- Ensure that the same divisor is not counted twice
15+
if complement ~= i then
16+
res = res + complement
17+
end
18+
end
19+
end
20+
return res
21+
end

0 commit comments

Comments
 (0)