Bac-style subjectBac Computer science

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.

  1. Question 1

    4 pts

    Write 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().

  2. Question 2

    6 pts

    Write 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.

  3. Question 3

    4 pts

    Write a function parfait(n) that returns True if n is perfect, False otherwise.

    parfait(28) → True

    Hint

    Reuse somme_diviseurs.

  4. Question 4

    6 pts

    Main 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.

We use cookies to keep you signed in and remember your language. Nothing is shared with advertisers.