Alexis
Alexis

Reputation: 1

How to find three consecutive perfect numbers?

I was asked to find three consecutive perfect numbers (i.e. numbers which factors(including 1 and excluding itself) sum up to be itself) after 6. Here is my attempt:

# Find three consecutive perfect numbers after 6
def f(x):
    "Find the sum of all factors."
    factors = []
    for i in range (1,x-1):
        if x%i == 0:
            factors.append (i)
        else:
            pass
    return sum(factors)

counts = 0
perfect_numbers = []
x = 6
while counts <= 2:
    x += 1
    if x == f(x):
        perfect_numbers.append (x)
        counts += 1
    else:
        pass
print(perfect_numbers)

As I run it, nothing shows up. I know there could be a really trivial mistake however I spent whole day searching for it and got nothing. Please help.

Upvotes: 0

Views: 135

Answers (1)

cdlane
cdlane

Reputation: 41903

Although your code only takes 3 seconds on my machine to calculate the desired result, we can cut that time in half by improving this line:

for i in range (1,x-1):

The next highest factor, after x itself, which we don't count, is x / 2 as 2 is the next smallest divisor after 1. This lets us rewrite the above as:

for i in range(1, x // 2 + 1):

Also, your use of range(1, x - 1) makes f(2) incorrect, should you want to reuse this code in another program later on. A rework of your code for the above and some style issues:

# Find three consecutive perfect numbers after 6

def f(x):
    "Find the sum of all factors."

    factors = []

    for i in range(1, x // 2 + 1):
        if x % i == 0:
            factors.append(i)

    return sum(factors)

count = 0
number = 6
perfect_numbers = []

while count < 3:
    number += 1

    if number == f(number):
        perfect_numbers.append(number)
        count += 1

print(perfect_numbers)

Upvotes: 1

Related Questions