Skip to content
Open
Show file tree
Hide file tree
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
2 changes: 2 additions & 0 deletions math/aliquot_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ func TestAliquotSum(t *testing.T) {
{"n = 10", 10, 8, nil},
{"n = 11", 11, 1, nil},
{"n = 1", 1, 0, nil},
{"n = 28", 28, 28, nil},
{"n = 36", 36, 55, nil},
{"n = -1", -1, 0, math.ErrPosArgsOnly},
{"n = 0", 0, 0, math.ErrNonZeroArgsOnly},
}
Expand Down
21 changes: 15 additions & 6 deletions math/aliquotsum.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,25 +5,34 @@
// is the sum of all proper divisors of n,
// that is, all divisors of n other than n itself
// wikipedia: https://en.wikipedia.org/wiki/Aliquot_sum
// time complexity: O(n)
// time complexity: O(sqrt(n))
// space complexity: O(1)
// author: Akshay Dubey (https://github.com/itsAkshayDubey)
// see aliquotsum_test.go

package math

// This function returns s(n) for given number
// AliquotSum returns the sum of all proper divisors of n.
func AliquotSum(n int) (int, error) {
switch {
case n < 0:
return 0, ErrPosArgsOnly
case n == 0:
return 0, ErrNonZeroArgsOnly
default:
var sum int
for i := 1; i <= n/2; i++ {
if n%i == 0 {
sum += i
if n == 1 {
return 0, nil
}

sum := 1
for divisor := 2; divisor <= n/divisor; divisor++ {
if n%divisor == 0 {
sum += divisor

pairedDivisor := n / divisor
if pairedDivisor != divisor {
sum += pairedDivisor
}
}
}
return sum, nil
Expand Down