Skip to content

Commit

Permalink
Add Aliquot sum (#18)
Browse files Browse the repository at this point in the history
  • Loading branch information
vil02 authored Nov 22, 2023
1 parent 90b32ed commit 2bd33e6
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
35 changes: 35 additions & 0 deletions .spec/math/aliquot_sum_spec.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
describe("Aliquot sum", function()
local aliquot_sum = require("math.aliquot_sum")

it("should handle general cases", function()
assert.equal(0, aliquot_sum(1))
assert.equal(1, aliquot_sum(2))
assert.equal(1, aliquot_sum(3))
assert.equal(1 + 2, aliquot_sum(4))
assert.equal(1, aliquot_sum(5))
assert.equal(1 + 2 + 3, aliquot_sum(6))
assert.equal(1, aliquot_sum(7))
assert.equal(1 + 2 + 4, aliquot_sum(8))
assert.equal(1 + 3, aliquot_sum(9))
assert.equal(106, aliquot_sum(80))
assert.equal(114, aliquot_sum(102))
assert.equal(312, aliquot_sum(168))
assert.equal(14, aliquot_sum(169))
assert.equal(154, aliquot_sum(170))
assert.equal(89, aliquot_sum(171))
assert.equal(533, aliquot_sum(1771))
assert.equal(7044, aliquot_sum(7852))
end)

it("should throw error when input is 0", function()
assert.has_error(function()
aliquot_sum(0)
end)
end)

it("should throw error when input is negative", function()
assert.has_error(function()
aliquot_sum(-1)
end)
end)
end)
21 changes: 21 additions & 0 deletions src/math/aliquot_sum.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
-- Computes the sum of proper divisors
-- of the input number of n, i.e.
-- sum of divisors of n that are less than n.
return function(n)
assert(n > 0, "input must be positive")
if n == 1 then
return 0
end
local res = 1
for i = 2, math.sqrt(n) do
if n % i == 0 then
res = res + i
local complement = n / i
-- Ensure that the same divisor is not counted twice
if complement ~= i then
res = res + complement
end
end
end
return res
end

0 comments on commit 2bd33e6

Please sign in to comment.