Perfect numbers
Hints and examples are shown, check as often as you like, no timer.
Subject
A number is perfect when it equals the sum of its proper divisors (all its divisors except itself). Example: 28 = 1 + 2 + 4 + 7 + 14.
Question 1
4 ptsWrite a function saisie() that reads an integer n with 2 ≤ n ≤ 1000 (repeat the input while n is invalid) and returns it.
saisie() ⟵ 28 → 28
Hint
Use a while loop around input() and int().
Question 2
6 ptsWrite a function somme_diviseurs(n) that returns the sum of the proper divisors of n.
somme_diviseurs(28) → 28
Hint
A proper divisor d of n satisfies n % d == 0 and d < n.
Question 3
4 ptsWrite a function parfait(n) that returns True if n is perfect, False otherwise.
parfait(28) → True
Hint
Reuse somme_diviseurs.
Question 4
6 ptsMain program: read n with saisie() then display "n est parfait" or "n n'est pas parfait" (e.g. 28 est parfait).
Inputs: 28 → 28 est parfait
Hint
print(n, "est parfait") prints the number, a space, then the text.
Your program
Saved automatically in this browser.
One line per input() call, used by “Run”.
Model solution
def saisie():
n = int(input("Donner n : "))
while not (2 <= n <= 1000):
n = int(input("Donner n : "))
return n
def somme_diviseurs(n):
s = 0
for d in range(1, n // 2 + 1):
if n % d == 0:
s = s + d
return s
def parfait(n):
return somme_diviseurs(n) == n
# Programme principal
n = saisie()
if parfait(n):
print(n, "est parfait")
else:
print(n, "n'est pas parfait")
The first run downloads Python (~6 MB) and can take a few seconds.