I am supposed to write a Python program that will identify and print all the perfect numbers in some closed interval [2, n], one per line.
We only should use nested while loops and if-else statements. I did it somehow using a for loop, but can't figure out the same using a while loop.
How could I translate my code into a while loop?
Here's what I have:
limit = int(input("enter upper limit for perfect number search: "))
for n in range(2, limit + 1):
sum = 0
for divisor in range(1, n):
if not n % divisor:
sum += divisor
if sum == n:
print(n, "is a perfect number")
This should work:
limit = int(input("enter upper limit for perfect number search: "))
n = 1
while n <= limit:
sum = 0
divisor = 1
while divisor < n:
if not n % divisor:
sum += divisor
divisor = divisor + 1
if sum == n:
print(n, "is a perfect number")
n = n + 1