Bac-style subjectBac MathematicsBac Experimental sciencesBac Technical sciences

Twin primes

Hints and examples are shown, check as often as you like, no timer.

Subject

Two prime numbers p and p + 2 are called twin primes, for example (11, 13). We want to list all twin primes up to n.

  1. Question 1

    4 pts

    Write a function saisie() that reads an integer n with 3 ≤ n ≤ 500 (repeat while invalid) and returns it.

    saisie() ⟵ 20 → 20

    Hint

    Same pattern as every Bac saisie: while not (condition).

  2. Question 2

    6 pts

    Write a function premier(x) that returns True if x is prime, False otherwise.

    premier(17) → True

    Hint

    1 is not prime. Test divisors from 2 while d * d <= x.

  3. Question 3

    5 pts

    Write a function jumeaux(n) that returns the list of tuples (p, p + 2) of twin primes with p + 2 ≤ n, in increasing order.

    jumeaux(20) → [(3, 5), (5, 7), (11, 13), (17, 19)]

    Hint

    Loop p from 2 to n - 2 and append (p, p + 2).

  4. Question 4

    5 pts

    Main program: read n with saisie(), then display each pair on its own line as "p q" (e.g. 3 5). If there is none, display "Aucun couple".

    Inputs: 20 → 3 5 ⏎ 5 7 ⏎ 11 13 ⏎ 17 19

    Hint

    for (p, q) in jumeaux(n): print(p, q)

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 (3 <= n <= 500):
        n = int(input("Donner n : "))
    return n


def premier(x):
    if x < 2:
        return False
    d = 2
    while d * d <= x:
        if x % d == 0:
            return False
        d = d + 1
    return True


def jumeaux(n):
    t = []
    for p in range(2, n - 1):
        if premier(p) and premier(p + 2):
            t.append((p, p + 2))
    return t


# Programme principal
n = saisie()
t = jumeaux(n)
if len(t) == 0:
    print("Aucun couple")
else:
    for (p, q) in t:
        print(p, q)

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.