Skip to content
Merged
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: 18 additions & 2 deletions maths/aliquot_sum.nim
Original file line number Diff line number Diff line change
@@ -1,6 +1,15 @@
## Aliquot sum
##
## In number theory, the aliquot sum s(n) of a positive integer n is the sum of
## all proper divisors of n, that is, all divisors of n other than n itself.
##
## For example:
## - s(12) = 1 + 2 + 3 + 4 + 6 = 16
## - s(1) = 0 (since 1 has no proper divisors)
##
## This function determines whether a positive integer is perfect (s(n) = n), abundant (s(n) > n), or deficient (s(n) < n).
##
## Reference:
## https://en.wikipedia.org/wiki/Aliquot_sum

runnableExamples:
Expand All @@ -12,9 +21,16 @@ runnableExamples:
echo fmt"The sum of all the proper divisors of {number} is {sum}"

func aliquotSum*(number: Positive): Natural =
## Returns the sum of all the proper divisors of the number
## Example: aliquotSum(12) = 1 + 2 + 3 + 4 + 6 = 16
## Compute the aliquot sum of a positive integer.
##
## Input:
## - number: a positive integer (number > 0)
## Output:
## - The sum of all proper divisors of 'number'
## Time Complexity: O(number)
## Space Complexity: O(1)
result = 0
# A proper divisor p satisfies `number = pq` with q greater than or equal to 2
for divisor in 1 .. (number div 2):
if number mod divisor == 0:
result += divisor
Expand Down