Finding perfect numbers with multiprocessing in Python

The History of the Theory of Numbers (1919) is a three-volume work by Leonard Eugene Dickson, summarizing work in number theory up to the year 1920. In this book a paragraph can be found on the first page, revealing that Perfect Numbers have engaged arithmeticians for a long time.

A perfect number is one, like 6=1+2+3, which equals the sum of its divisors other than itself.

Leonard Eugene Dickson

The first four such numbers 6, 28, 496 and 8128 were discovered a very long time ago, whereas the fifth 33550336 was not found before year 1456.

Screenshot from an old text book about perfect numbers.
Screenshot from an old text book about perfect numbers.

Today, we are lucky to have computing power to aid us in the treasure hunt, as calculating these must have taking a lot of time for the brilliant mathematicians.

I had not utilized multiprocessing before and decided that now is the time to look that up and see how it might improve computing tasks for me with Python. Look at other posts in the recreational mathematics category and you will find examples on such tasks.

Instead of letting a program run one number at the time, multiprocessing let me split the task on a larger workforce, in my case eight CPU cores.

Using a linux command line tool called htop, the latter image below shows how all CPU cores are in use, compared to the former one:

The terminal program htop show one core in use
The terminal program htop show multiple cpu cores in use

Splitting the job on a larger group of workers instead of just one, is very similar to for example a housebuilding project, where a manager manage a group of builders instead of doing everything by her or himself.

Using the time command in linux, I can see just much quicker it is too:

$ time python perfect_numbers.py
Found a perfect number, 6
Found a perfect number, 28
Found a perfect number, 496
Found a perfect number, 8128
[6, 28, 496, 8128]

real 1m54,014s
user 1m54,202s

$ time python perfect_numbers_multicpu.py
Found a perfect number, 6
Found a perfect number, 28
Found a perfect number, 496
Found a perfect number, 8128
[6, 28, 496, 8128]

real 0m42,665s
user 5m3,504s

Great joy with number theory and good practice using multiprocessing.