Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Perfect numbers
#1
Gentlemans, do you have any suggestions why this code doesn't output proper values?

When I write end = 100 it outputs:
[6, 24, 28]

24 is not a perfect number.

def perfect_number(end = 100):

    lista = []
    for n in range(2, end):
        sum = 0
        for x in range(1, n):
            if n % x == 0:
                sum += x
            if sum == n:
                lista.append(n)
                sum = 0
    return lista
print(perfect_number())
Reply
#2
You should be checking if after you get *all* the factors of a number, that they sum to that number. But that's not what your code does.

Your code is checking the sum after every number check (even the ones that aren't factors). If the sum to that point is equal to the number, then you add it.

In the case of 24, the factors are:
1, 2, 3, 4, 6, 8 => sums to 24, you declare a match...
Oops, 12 is also a factor. Sum is now 36, but it's too late. It's already added.

Basically, you shouldn't be looking at the sum inside the inner loop.
Reply
#3
That's true I find it just seconds before:

"The if (sum == n) check needs to be done outside the loop. Otherwise you might pick up numbers such that the sum of a subset of divisors equals the number.

In fact, 24 is one such example since 1+2+3+4+6+8=24. Your code prematurely concludes that 24 is perfect, despite it also being divisible by 12."

This is good:

def perfect_number(end = 9001):

    lista = []
    for n in range(2, end+1):
        sum = 0
        for x in range(1, n):
            if n % x == 0:
                sum = sum + x
        if sum == n:
            lista.append(n)
            
    return lista
print(perfect_number())
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Are there errors in the code for my coin toss systems? Matlibplot is too perfect . Coolkat 0 368 Nov-13-2023, 11:54 AM
Last Post: Coolkat
  Runs perfect in Python but fails to print last statement when converted to .exe. Help sunil422 3 2,803 Aug-13-2020, 01:22 PM
Last Post: deanhystad
  Print Numbers starting at 1 vertically with separator for output numbers Pleiades 3 3,718 May-09-2019, 12:19 PM
Last Post: Pleiades
  Finding perfect numbers BillMcEnaney 6 4,378 Apr-04-2019, 04:46 AM
Last Post: BillMcEnaney
  Help with try and open 6.txt file and print as perfect or not Pleiades 13 5,186 Jan-03-2019, 10:14 PM
Last Post: Pleiades
  Perfect Number formula in Python Question an Mersenne Numbers Pleiades 5 6,040 May-16-2018, 04:56 PM
Last Post: Pleiades

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020