I am making an algorithm with python to find perfect numbers up to 100000000000000. I have created some code for this that should do it, and it does not throw up any errors, but the code just outputted nothing and is running continuously. I have checked, and the first perfect number is six, so why is my program taking so long to get there?
Here is my code:
number = 1
divisor = 2
factors = 1
if number < 100000000000000:
while True:
number2 = number/divisor
if isinstance(number2, int):
factors = factors + divisor + number2
divisor = divisor + 1
if divisor == number:
if factors == number:
print(number)
number = number + 1
break
In both of these examples, I used the variable "j" for the target number.
This was my first thought, but please do not use it on anything bigger than 10000:
print([i for i in range(1,j+1) if i == sum(k for k in range(1,i//2+1) if i%k == 0)])
Since perfect numbers cannot be prime, I decided to alter a sieve to reduce the amount of numbers to calculate. The sieve can be found here Sieve of Eratosthenes. There is a good explanation there and on the wiki about the sieve.
def SieveOfEratosthenes(n):
prime = [True for i in range(n+1)]
p = 2
while (p * p <= n):
if (prime[p] == True):
for i in range(p * 2, n+1, p):
prime[i] = False
p += 1
for p in range(2, n):
if not prime[p]:
#this is my change
if p == sum(k for k in range(1,p//2+1) if p%k == 0):
yield p
a = SieveOfEratosthenes(j)
b = next(a)
print(b)
try:
while b < j:
b = next(a)
print(b)
except StopIteration:
print("Done")
These work in theory, but I can't get it to work in a "reasonable" amount of time.
Hopefully these will help until someone can post a more efficient solution.