Given a sorted array of integers and we have to find all Pythagorean triples.
Definition from Wikipedia : A Pythagorean triple consists of three positive integers a, b, and c, such that a2 + b2 = c2. Such a triple is commonly written (a, b, c), and a well-known example is (3, 4, 5).
Code :
public static void PythagoreanTriple(int[] input) { int length = input.Length; if (length < 3) { Console.WriteLine("Length of Array can not be less then 3"); return; } for (int i = 0; i < length; i++) { input[i] = input[i] * input[i]; } int leftPointer = 0; int rightPointer = 0; int temp = 0; for (int i = length - 1; i > 1; i--) { leftPointer = 0; rightPointer = i - 1; temp = input[i]; ; while (leftPointer < rightPointer) { if (input[leftPointer] + input[rightPointer] == temp) { Console.WriteLine(Math.Sqrt(input[leftPointer]) + ";" + Math.Sqrt(input[rightPointer]) + ";" + Math.Sqrt(input[i])); break; } else if (input[leftPointer] <= input[rightPointer]) { leftPointer++; } else { rightPointer--; } } } }
Test Case:
Input | Output |
{ 1, 3, 4,5, 6, 7, 8, 10, 11 } | 6;8;10
3;4;5 |
{ 1, 3, 4,5, 6, 7, 8, 10, 11,12,13 } | 5;12;13
6;8;10 3;4;5 |
{ 5, 6, 7, 8, 10, 11,12,13,14,15,17 } | 8;15;17
5;12;13 6;8;10 |
Filed under:
Array
Leave a comment