A perfect number is a number whose factors, including the number itself, sum up to twice the number. For example,6 is a perfect number since its factors (1, 2, 3, 6) sum up to 12.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | # Filename: perfect.py
a = True
n = 0
while a == True: # To loop the following commands
running = True
while running == True:
r = 0
n = n+ 1
for x in range(1,n + 1):
if n%x == 0: # To determine the factors of n
r = r + x
if x == n:
if r == 2*n:
print n
running = False
else:
running = False
|
I got the idea for writing a program to generate perfect numbers from a website which had posted the problem of generating them as a challenge. I took up the challenge and decided to write a program in Python to accomplish that.Solutions for the problem in other languages are there on the page, but nobody had posted a solution in Python.
Here's the aforementioned url: http://code.box.sk/
Hi!
Here's a slightly shorter version ;)
Regards, Markus
Even shorter :)
Thanks Markus! I'm new to python (and programming), and your solutions have taught me a lot about economy and style in writing code. Any further suggestions would be equally welcome. :) Regards, Aditya
Thanks Markus! I'm new to Python (and programming) and your solutions have taught me a lot about economy and style in writing code. Any further suggestions about style will be equally welcome. :) Regards, Aditya
For-loops simplify the code.
Optimization. The following runs a lot faster, at the cost of some typing. (Finding perfect numbers with python is going to be slow no matter what, so I suppose it is a silly problem to optimize).
Mainly--you only need to search factors up to the square root of n.
precomputed values. As with just about anything dealing with primes, the fastest way to generate values is to start with precomputed values. In this case the perfect numbers can be generated from Mersenne primes, and there are only 42 or so of those which are known. Testing Mersenne candidates is faster than the general prime factor generation algorithms shown here so if you don't want to stop with a ValueError you might want to implement one of them instead, or use a service which connects to the Great Mersenne Prime Search server.
More details at http://mathworld.wolfram.com/PerfectNumber.html .
yield -> raise. Err, change that "yield ValueError," into a "raise ValueError,". As you might guess, I didn't make it that far in my testing. :)