Facile 0 résolus 0 % de réussite

Twin Primes

List all twin prime pairs (p, p + 2) up to a limit.

Ce que vous allez apprendre

  • Mark the primes up to a limit with a sieve
  • Scan for primes that are two apart
  • Handle limits too small to hold any pair

Problème

Afficher la traduction

Twin primes are two primes that differ by 2, such as 11 and 13 or 17 and 19. Find every such pair whose larger member is at most limit.

Implement twin_primes(limit).

For large limits, find all primes at once with a sieve instead of testing each number separately.

Input

limit: The largest value the larger prime of a pair may have.

Output

Return a list of pairs [p, p + 2] where both numbers are prime and p + 2 ≤ limit, sorted by p in ascending order. If there are none, return an empty list.

Contraintes

0 ≤ limit ≤ 10^6

Exemples

Exemple 1
Entrée :
limit = 20

Sortie attendue :
expected = [
    [3, 5],
    [5, 7],
    [11, 13],
    [17, 19]
]
Entrée :
long long limit = 20;

Sortie attendue :
std::vector<std::vector<long long>> expected = {
    {3, 5},
    {5, 7},
    {11, 13},
    {17, 19}
};
Entrée :
long limit = 20;

Sortie attendue :
long[][] expected = new long[][] {
    new long[] {3, 5},
    new long[] {5, 7},
    new long[] {11, 13},
    new long[] {17, 19}
};

Explication

The primes up to 20 are 2, 3, 5, 7, 11, 13, 17, 19; the ones 2 apart give [[3, 5], [5, 7], [11, 13], [17, 19]].

Exemple 2
Entrée :
limit = 6

Sortie attendue :
expected = [
    [3, 5]
]
Entrée :
long long limit = 6;

Sortie attendue :
std::vector<std::vector<long long>> expected = {
    {3, 5}
};
Entrée :
long limit = 6;

Sortie attendue :
long[][] expected = new long[][] {
    new long[] {3, 5}
};

Explication

3 and 5 are both prime and 5 ≤ 6, but 7 is above the limit, so only [[3, 5]].

Comment l'aborder

Essayez d'abord seul, puis ouvrez les indices un par un.

Indice 1

A sieve finds all primes up to 10^6 much faster than testing each number.

Indice 2

Then check every p with p + 2 ≤ limit.

Indice 3

The first pair is (3, 5), so any limit below 5 gives an empty list.

Complexité attendue

O(limit log log limit) time, O(limit) extra space

Références

Ce défi a été adapté pour CodeUtility. Suivez l'énoncé et les contraintes ci-dessus.

La meilleure solution validée de chaque codeur. Les plus rapides, les plus légères et les mieux notées passent devant.

Aucune solution validée pour l'instant. Résolvez-le et prenez la première place.

Apprenez des autres

Solutions de la communauté

Aucune solution publiée pour l'instant. Résolvez ce défi pour partager la première.