right angle triangle

I wrote this code to get a number from user and if it is possible to make a right angle triangle with it I want it to give out the numbers from smallest to biggest one it works properly but I want to know if there is a more efficient way(giving the result faster) to code such thing.
it's working slowly it's a long process to find the answer I want to make it faster
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
 #include <iostream>
using namespace std;
int main(){    int n,i,j,k,x=1,y=1,z=1;
cin>>n;
for(i=1;i<n;i++){
	for(j=1;j<i;j++){
		for (k=1;k<=j;k++){
			if(k*k+j*j==i*i && i+j+k==n){
				x=0;
				y=0;
				break;
			}
			
		}
		if(y==0)
		break;
	}
	 if(x==0)
			break;


}
	 if(x==0)
cout<<k<<" "<<j<<" "<<i;
else
cout<<"Impossible";	
	return 0;
}
Last edited on
You don't need the third inner loop: you are only interested in the case k = n - i - j.

You can also limit the upper range of the j loop; it can't be bigger than n - i - 1.

You can also work out in advance a look-up table of squares, to avoid repeatedly calculating the same multiplication product.
Last edited on
Breaking out from nested loops can be neater with a function:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>

bool isTriangle( int n, int& i, int& j, int& k )
{
    for ( i=1; i<n; ++i ) {
	    int ii = i*i; // cache value
	    for ( j=1; j<i; ++j ) {
		    for ( k=1; k<=j; ++k ) {
			    if ( k*k+j*j==ii and i+j+k==n ) {
			        return true;
			    }
		    }
	    }
    }
    return false;
}

int main()
{
	int n=0, a, b, c;
	// input can fail or have insane value:
	if ( std::cin >> n and 0 < n and isTriangle( n, a, b, c ) )
		std::cout << c << " " << b << " " << a;
	else
		std::cout << "Impossible";	

	return 0;
}
Topic archived. No new replies allowed.