-2

I wrote a code that outputs "Yes" when the input number is a perfect number, and outputs "No" when the number isn't. But when I input 6, it outputs "No". I have specified it to print "Yes" with if-else statements when the sum of divisors equal to the original input. Why is the output wrong?

n=int(input())

myList=[]

for i in range(1,n):
    if n%i==0:
        myList.append(n)

sum=0
for i in range(0,len(myList)):
    sum=sum+myList[i]

if sum==n:
    print("Yes")
else:
    print("No")
Yolanda Hui
  • 97
  • 1
  • 1
  • 8

2 Answers2

1

Sorry for the confusion regarding my previous answer. The problem was that you were appending n instead of i in myList.append(n). Moreover, you could simply use sum to sum your list.

Your output was wrong because you were appending the number n and hence when you do sum=sum+myList[i], you were just adding n to the sum three times because instead of adding 1, 2, 3 to sum, you were adding 6, 6, 6.

n=int(input())
myList=[]

for i in range(1,n):
    if n%i==0:
        myList.append(i)

if sum(myList)==n:
    print("Yes")
else:
    print("No")

A one liner suggested by Matthias

print(('No', 'Yes')[sum(i for i in range(1, n) if not n % i) == n])
gboffi
  • 22,939
  • 8
  • 54
  • 85
Sheldore
  • 37,862
  • 7
  • 57
  • 71
  • 1
    Just for fun (and to show the power of Python) a one-liner: `print(('No', 'Yes')[sum(i for i in range(1, n) if not n % i) == n])` – Matthias Oct 02 '18 at 12:57
  • @Matthias: I am a fan of one liner but I guess the OP might find it confusing. Anyway, would you mind if I add your one liner in my answer with proper acknowledgement to you? – Sheldore Oct 02 '18 at 12:58
  • @Bazingaa: My comment wasn't meant as an answer. You can add it, but for a beginner it will be confusing as you said. – Matthias Oct 02 '18 at 13:02
  • @Matthias: I added your suggestion – Sheldore Oct 02 '18 at 13:25
0

There is a cool one liner in comment section of this answer

other have already pointed out your mistake so here is how you can optimize your code a little bit.

greatest divisor of 6( =n) other than 6 is 3( = n//2) since we don't add number itself to factors_sum while checking whether sum of factors equals to number( ie while finding perfect number),so we don't need to check whether any number greater than 3 is a factor of 6 or not.

# perfect nums example 6, 28, 496, and 8,128
n = 8128
stop = (n//2) +1 # stop is exclusive thats why extra 1    
factors_sum = 0

for i in range(1,stop):
    if n % i == 0:
        factors_sum += i

print('Yes' if factors_sum == n else 'No') # Yes

'''
benchmark result( using timeit ran each five times)
for smaller value of n there is no significant difference but as the value of n becomes very large you can clear see the difference.
n = 33550336
1)    stop = (n//2) +1
      6.580396663 ( time in secs)

2)    stop = n
      12.635774489000001 ( time in secs)
'''
Tanmay jain
  • 814
  • 6
  • 11