everyone. I have a question about an exercise from Brian Heinold's A Practical Introduction to Python Programming that reads "A number is called a perfect number if it is equal to the sum of all of its divisors, not including the number itself. For instance, 6 is a perfect number because the divisors of 6 are 1, 2, 3, 6 and 6 = 1 + 2 + 3. As another example, 28 is a perfect number because its divisors are 1, 2, 4, 7, 14, 28 and 28 = 1 + 2 + 4 + 7 + 14. However, 15 is not a perfect number because its divisors are 1, 3, 5, 15 and 15 ̸= 1 + 3 + 5. Write a program that finds all four of the perfect numbers."
I'm a beginner. I tried. My code doesn't work. Please tell me where did I go wrong and why does the program print the number 1 endlessly why I press Run.
Thank you.
# We have to check all numbers from 1 to 10000.
for i in range(1,10001):
# Since all numbers are divisible by 1,
#we can set 1 as the initial value.
sum_div = 1
#The potential divisors also range from 1 to 10000,
#therefore we can use this nested loop:
for j in range(1,20001):
# A j value can be a divisor if the remainder is zero.
# AND the range of the divisors must not include the number itself.
# Since 1 is already known to be a divisor, we can start checking from 2.
if i % j == 0 and j != i:
#We already have 1 as the first divisor,
#so now we have to add the other divisors.
sum_div = sum_div + j
#If the sum of the divisors equals the number,
#then we got the number we need.
if sum_div == i:
print(i)