Suppose you are given hypotenuse of a right angled triangle,then how can you determine whether there are two integral smaller sides possible with the given hypotenuse.
For example, you are given hypotenuse as 5.Then you have to determine whether you have smaller integral sides for the given right triangle.The answer will be yes
because we can have smaller sides as 3 and 4,hence getting a 3-4-5 right triangle.
Similarly,for hypotenuse as 7 we can have no such right triangle.
In other words,we have to find whether a given number N can serve as hypotenuse for a right triangle with all 3 sides as integers.
I went through entire article on Pythagorean triples but still no success.I am confused what conditions to check.Please help.
What about this one?
-> 2 for loops continues to the hypotenuse. something like this one:
Test:
Output:
O(N)
You have for a primitive pythagorean triple:
Suppose p >= q. Then we have
Suppose N = 13. Then we need q <= sqrt(13 / 2) = 2.54
q = 2 => p^2 = 13 - 4 = 9, which is a square.
Hence you can have a small loop of numbers 'i' from 1..sqrt(N/2) and check if N - (i^2) is a square.
This will be O(sqrt(N)) for a member of a primitive pythagorean tuple.
Sample code in C/C++:
Output:
This question has been one of my most searched topics on the net. But solution is simple. Coming to the answer let n can be hypotenuse of a right angled triangle. n^2 = a^2 + b^2. (n,a and b are integers). Then obviously for any integer k, k*n can be hypotenuse. Any prime number of the form (4*l+1) can be hypotenuse (l is an integer). So, split a number into its prime factors. If at least one of the prime factor is in the form 4*l+1 , then obviously the number can be hypotenuse. Eg : 5 can be expressed as 4*1+1 and 5^2 = 3^2 + 4^2. Similarly, 78 = 2*3*13 and 13 can be expressed as 4*3+1. and 13^2 = 5^2 + 12^2 =>78^2 = 30^2 + 72^2
EDIT: NO need to perform the following step, because it will always return false.
.
Complexity : O(N)
EDIT: As Dukeling points out, there is no need to store an array. You can directly square I1 and I2 as you go.