简体   繁体   中英

Why is my Python code displaying the wrong result?

I have a code that reads 2 integers, m and n, and prints all the perfect numbers between m and n (inclusive m and n). If I input 2 and 7, it should give me 6. But it gives me 13. What went wrong?

m=int(input())
n=int(input())

myList=[]

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

sum=0
for i in range(0,len(myList)):
    sum=sum+myList[i]
    for j in range(m,n+1):
        if sum==j:
            sum=j

print(sum)

You're making this more complicated than it needs to be. You need one nested loop to solve this. Iterate through every number in your range, set a value x equal to 0 and every time you find a number that divides evenly, add it to x. If at the end of your inner loop, x == i, then you have a perfect number and print it out. If you need it in a list, append it to your list. You're trying to save all the intermediate numbers, just save the result if you find it.

for i in range(m,n+1):
    x = 0
    for j in range(1,i):
        if i % j == 0:
            x += j
    if i == x:
        print(i)

What you want to do is something like this.

Add all the divisors of a number expect the number itself into a list then check if the sum of that list is equal to the number . If it is equal print the number else take the next number

m=int(input())
n=int(input())


for i in range(m,n+1):

    myList=[]
    for j in range(1,i):
        if i%j==0:
            myList.append(j)
    if sum(myList)==i:
        print(i)

Input

2
7

Output

6

you should iterate to n/2, since any "number" cant be divisible by any number which is greater than half of "number".

for i in range(m, n+1):
    _sum = 0
    for j in range(1, int(i/2)+1):
        if i%j==0:
            _sum += j
    if _sum==i:
       print(i)
m=int(input())
n=int(input())

'''
mylist =[]  instead of using myList to keep track of factors 
just use sum_of_factors_of_i variable and keep adding newly found factors to 
it by doing so you will not need to loop over myList to get sum.
'''
for i in range(m,n+1):
    sum_of_factors_of_i = 0
    for j in range(1,i):
        if i%j==0:
            sum_of_factors_of_i += j

    if sum_of_factors_of_i == i:
        print(i)

'''        
input 
2
7

output
6
----------------------------------
input
2
30

output
6
28
'''

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM