Retour aux défis
Moyen 0 résolus 0 % de réussite

Find Right-Triangle Triples

List all integer right triangles with a specified perimeter.

Ce que vous allez apprendre

  • List all integer right triangles for a perimeter
  • Avoid duplicates by ordering sides
  • Prune the search with bounds

Problème

Afficher la traduction

Find every triple of positive integers a < b < c for which a² + b² = c² and a + b + c = perimeter. Return each triple as [a, b, c], ordered by increasing a and then b. Do not include permutations of the same sides.

Implement pythagorean_triplets(perimeter).

Input

perimeter: The required sum of all three sides.

Output

Return a list of triples in the specified order.

Contraintes

3 ≤ perimeter ≤ 100,000. Return an empty list if no triangle qualifies.

Exemples

Exemple 1
Entrée :
perimeter = 30

Sortie attendue :
expected = [
    [5, 12, 13]
]
Entrée :
long long perimeter = 30;

Sortie attendue :
std::vector<std::vector<long long>> expected = {
    {5, 12, 13}
};
Entrée :
long perimeter = 30;

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

Explication

5 + 12 + 13 = 30 and 5² + 12² = 13². This is the only qualifying triple.

Exemple 2
Entrée :
perimeter = 11

Sortie attendue :
expected = []
Entrée :
long long perimeter = 11;

Sortie attendue :
std::vector<std::vector<long long>> expected = {};
Entrée :
long perimeter = 11;

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

Explication

No increasing positive integer right-triangle triple sums to 11.

Comment l'aborder

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

Indice 1

A valid triple must satisfy both the Pythagorean equation and the perimeter sum.

Indice 2

Use the perimeter to limit the search instead of trying every ordering of sides.

Indice 3

Remember to keep only a < b < c, and skip duplicates from symmetric side choices.

Complexité attendue

O(n^2) time, O(1) extra space

Références

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

Apprenez des autres

Solutions de la communauté

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