• 1
    Input and Output Data
    • Tasks
  • 2
    Conditions
    • Tasks
  • 3
    For Loop
    • Tasks
  • 4
    Strings
    • Tasks
  • 5
    While Loop
    • Tasks
  • 6
    Lists
    • Tasks
  • 7
    Two-Dimensional Arrays
    • Tasks
  • 8
    Dictionaries
    • Tasks
  • 9
    Sets
    • Tasks
  • 10
    Functions and Recursion
    • Tasks
  • к

Занятие 5. While cycle

Difficulty level:

Task«Perfect number»

you strive to join the secret "fraternity of digital Pythagoreans." This ancient society believes that the numbers rule the universe, and special, "perfect" numbers, store the key to the harmony of the world. To prove your value, you must pass the “test of perfection”.

rn

The program receives a sequence of natural numbers to the input, each on a new line. The input ends with the number 0. For each entered number (except 0), it is necessary to determine whether it is perfect.

rn

certificate: the completed number & mdash; This is a natural number equal to the sum of all their own divisors (that is, all positive divisors, different from the number itself). For example, for the number 6, their own dividers are 1, 2 and 3. Their amount is 1 + 2 + 3 = 6, which means 6 & mdash; Perfect number.

Input format

Entires are supplied to the input of the program, each on a new line. The last number in the sequence is always 0. This number & mdash; A sign of the end of the input, and it is not necessary to process it.

Output format

For each number from the input sequence (except 0), the program must derive the word "yes" on a separate line, if the number is completed, and "no", if not.

Example

Input

6
28
12
1
0

Output

Yes
Yes
No
no

Hint

There will be no clue here, decide for yourself!

main.py
Test 1
Test 2
Test 3
Test 4
Test 5
Test 6
Test 7
Test 8
Test 9
Test 10
Developer’s solution
def is_perfect(n):
    """
    Проверяет, является ли число n совершенным.
    """
    # Совершенные числа по определению больше 1.
    if n <= 1:
        return False

    # Начинаем сумму с 1, так как 1 - делитель любого числа.
    sum_of_divisors = 1
    
    # Ищем делители до квадратного корня из n.
    # Это эффективный способ, так как делители ходят парами.
    # Например, для 28: (2, 14), (4, 7).
    for i in range(2, int(n**0.5) + 1):
        if n % i == 0:
            sum_of_divisors += i
            # Добавляем парный делитель, если он не равен самому корню
            if i * i != n:
                sum_of_divisors += n // i

    # Сравниваем сумму делителей с исходным числом.
    return sum_of_divisors == n

# Основной цикл программы
while True:
    try:
        number = int(input())
        # Если ввели 0, завершаем программу.
        if number == 0:
            break
        
        if is_perfect(number):
            print("YES")
        else:
            print("NO")
            
    except (ValueError, EOFError):
        # Обработка некорректного ввода или конца файла
        break

🎉 Congratulations! 🎉

You did an excellent job with the task! It was a challenging problem, but you found the correct solution. You are one step closer to mastering programming! Keep up the good work, because every stage you pass makes you even stronger.

AD

Advertisement

red-snake blue-snake green-snake

Running your code...

Помощник ИИ

Привет! Я твой помощник по программированию. Задавай любые вопросы по Python, я могу рассказать о функциях, методах, обьяснить то, что тебе не понятно, а так же о текущей задаче!