Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (16.4k points)

So I should compose a Python program that will distinguish and print all the perfect numbers in some closed interval [ 2, n ], one for every line. We just need to utilize nested while loops/if-else conditional statements. I did it some way or another utilizing a for loop, yet can't sort out a similar utilizing same while loop. I'd value your assistance on the off chance that you could tell me the best way to make a translation of my code into a while loop. Thanks in advance. This is 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")

1 Answer

0 votes
by (26.4k points)

Try the following code:

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

Want to become an expert in python? Join the python course fast!

Browse Categories

...