Pythonmatics

Solving mathematical problems with Python

Perfect numbers


A perfect number is a number that equals the sum of its divisors, excluding the number itself. The first number that comes to mind is 6, as its divisors are 1, 2, and 3, and 1 + 2 + 3 = 6. The next perfect number is 28 (1 + 2 + 4 + 7 + 14 = 28). There is a magical connection between perfect numbers and specific prime numbers called Mersenne primes.

It is still unknown whether there are any odd perfect numbers. Additionally, it is unclear whether the number of perfect numbers is finite or infinite. Unsolved problems in mathematics are true mysteries. It is puzzling how there are problems that can be described to a 10-year-old that still remain unresolved. Questions regarding the existence of odd perfect numbers or whether perfect numbers are finite or infinite are good examples of these mysteries.

Finding all the perfect numbers between 1 and 10,000 can be achieved using a brute force algorithm, meaning going over every number and checking if it is a perfect number. There is nothing fancy with brute force programming; it relies on the computer’s ability to run many calculations quickly and find the solution.

It’s Python time

for x in range(1,10000):                             # go over all the numbers between 1 and 10000
   divisors = [d for d in range(1,x) if x % d == 0]  # collect all the devisors of the candidate
   if sum(divisors) == x:                            # check for perfectness
      print(x,divisors)

Output

6 [1, 2, 3]
28 [1, 2, 4, 7, 14]
496 [1, 2, 4, 8, 16, 31, 62, 124, 248]
8128 [1, 2, 4, 8, 16, 32, 64, 127, 254, 508, 1016, 2032, 4064]

Discover more from Pythonmatics

Subscribe now to keep reading and get access to the full archive.

Continue reading