Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Algorithm to determine whether a given number N can become hypotenuse of right triangle with all 3 integral sides

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.

like image 318
Naveen Avatar asked Oct 12 '13 10:10

Naveen


People also ask

How can you identify the hypotenuse of any right triangle?

The hypotenuse of a right triangle is always the side opposite the right angle. It is the longest side in a right triangle.

How can you use the Pythagorean theorem to determine if a triangle is a right triangle?

It is possible to determine if a triangle contains a right angle using Pythagoras' theorem . If the squares of the two shorter sides add up to the square of the hypotenuse, the triangle contains a right angle.

How do you determine if the side lengths could form a right triangle?

If the square of the length of the longest side of a triangle is equal to the sum of the squares of the other two sides, then the triangle is a right triangle. That is, in ΔABC, if c2=a2+b2 then ∠C is a right triangle, ΔPQR being the right angle.


1 Answers

You have for a primitive pythagorean triple:

(p^2 - q^2)^2 + (2 * p * q))^2 = (p^2 + q^2)^2 = N^2

Suppose p >= q. Then we have

N >= 2 * q^2 or q <= sqrt(N / 2)

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++:

#include <stdio.h>
#include <math.h>

void CheckTuple(int n)
{
    int k = sqrt(n/2.0);

    for (int i = 1; i <= k; i++) {
        int tmp = sqrt((double)(n - i * i));
        if ((tmp * tmp) == (n - i * i)) {
            printf("%d^2 + %d^2 = %d^2\n", (tmp*tmp - i*i), 2 * tmp * i, n);
            return;
        }
    }
    printf("%d is not part of a tuple\n", n);
    return;
}


int main(int argc, char *argv[])
{

    CheckTuple(5);
    CheckTuple(6);
    CheckTuple(13);
    CheckTuple(10);
    CheckTuple(25);

    return 0;
}

Output:

3^2 + 4^2 = 5^2
6 is not part of a tuple
5^2 + 12^2 = 13^2
8^2 + 6^2 = 10^2
7^2 + 24^2 = 25^2
like image 168
user1952500 Avatar answered Sep 16 '22 23:09

user1952500