Torna alle sfide
Media 0 risolte 0% di accettazione

Find Right-Triangle Triples

List all integer right triangles with a specified perimeter.

Cosa imparerai

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

Problema

Mostra traduzione

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.

Vincoli

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

Esempi

Esempio 1
Input:
perimeter = 30

Output atteso:
expected = [
    [5, 12, 13]
]
Input:
long long perimeter = 30;

Output atteso:
std::vector<std::vector<long long>> expected = {
    {5, 12, 13}
};
Input:
long perimeter = 30;

Output atteso:
long[][] expected = new long[][] {
    new long[] {5, 12, 13}
};

Spiegazione

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

Esempio 2
Input:
perimeter = 11

Output atteso:
expected = []
Input:
long long perimeter = 11;

Output atteso:
std::vector<std::vector<long long>> expected = {};
Input:
long perimeter = 11;

Output atteso:
long[][] expected = new long[][] {};

Spiegazione

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

Come affrontarlo

Prova prima da solo, poi apri un suggerimento alla volta.

Suggerimento 1

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

Suggerimento 2

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

Suggerimento 3

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

Complessità attesa

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

Riferimenti

Questa sfida è adattata per CodeUtility. Segui la traccia e i vincoli sopra.

Impara dagli altri

Soluzioni della community

Nessuna soluzione pubblicata. Risolvi questa sfida per condividere la prima.