Skip to content

Exercise: Perfect numbers

Perfect numbers are positive integers that are equal to the sum of their divisors. Here we have provided example Python and R scripts that should print all of the perfect numbers up to 1,000.

You can download each script to debug on your own computer:

perfect_numbers.py
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#!/usr/bin/env python3
"""
This script prints perfect numbers.

Perfect numbers are positive integers that are equal to the sum of their
divisors.
"""


def main():
    start = 2
    end = 1_000
    for value in range(start, end + 1):
        if is_perfect(value):
            print(value)


def is_perfect(value):
    divisors = divisors_of(value)
    return sum(divisors) == value


def divisors_of(value):
    divisors = []
    candidate = 2
    while candidate < value:
        if value % candidate == 0:
            divisors.append(candidate)
        candidate += 1
    return divisors


if __name__ == '__main__':
    main()
perfect_numbers.R
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#!/usr/bin/env -S Rscript --vanilla
#
# This script prints perfect numbers.
#
# Perfect numbers are positive integers that are equal to the sum of their
# divisors.
#


main <- function() {
  start <- 2
  end <- 1000
  for (value in seq.int(start, end)) {
    if (is_perfect(value)) {
      print(value)
    }
  }
}


is_perfect <- function(value) {
  divisors <- divisors_of(value)
  sum(divisors) == value
}


divisors_of <- function(value) {
  divisors <- c()
  candidate <- 2
  while (candidate < value) {
    if (value %% candidate == 0) {
      divisors <- c(divisors, candidate)
    }
    candidate <- candidate + 1
  }
  divisors
}


main()

But there's a problem ...

If we run these scripts, we see that they don't print anything:

How should we begin investigating?

Interactive debugger sessions

If your editor supports running a debugger, use this feature! See these examples for RStudio, PyCharm, Spyder, and VS Code.

Some initial thoughts ...
  • Are we actually running the main() function at all?

  • The main() function is almost certainly not the cause of this error.

  • The is_perfect() function is very simple, so it's unlikely to be the cause of this error.

  • The divisors_of() function doesn't look obviously wrong.

  • But there must be a mistake somewhere!

  • Let's use a debugger to investigate.