196. Python Program to Check If a Number Is a Perfect Number
EasyPhase 1 · Warm-up
This one uses a for loop, if and the % sign. You already know all three.
Overview
Checking for a perfect number is a classic interview question. It tests if you can find divisors with % and add them up in a loop.
Problem Statement
Fatima's maths teacher talks about perfect numbers today.
A divisor of a number divides it with nothing left over. A proper divisor is a divisor that is smaller than the number itself. A perfect number equals the sum of its proper divisors.
For example, the proper divisors of 6 are 1, 2 and 3, and 1 + 2 + 3 = 6. So 6 is a perfect number.
Read a number n. Print <n> is a perfect number or <n> is not a perfect number.
Steps
- Read
nand turn it into a whole number. - Start a total at 0.
- Loop over every number from 1 up to
n - 1. If it dividesnwith nothing left over, add it to the total. - If the total equals
n, it is a perfect number. Print the right line.
Examples
Example 1. Input 6 gives:
6 is a perfect number
Why: the proper divisors of 6 are 1, 2 and 3, and 1 + 2 + 3 = 6.
Example 2. Input 8 gives:
8 is not a perfect number
Why: the proper divisors of 8 are 1, 2 and 4, and 1 + 2 + 4 = 7. 7 is not 8.
Input
One whole number n (1 to 10000). Use input() with no prompt text: the tests type the input for you, and a prompt would end up in your output.
Output
One line: <n> is a perfect number or <n> is not a perfect number. The tests try 6 different inputs, also 1.
Try it first. The solution opens when you solve this question, or after 3 tries with Submit.