Pythagoras triplet code error

This code is not working for two test cases out of five. Please tell the error.
Question : Given a number N (denoting one of the legs of the triangle), Print its Pythagoras pair in increasing order if they exist. Otherwise, print ā€œ-1ā€.
N <= 10^9

code:
#include
#include<math.h>
using namespace std;
int main() {
long long int n,t,a,b,c,A,B,C;
int one=1, zero=0;
cin>>n;
if(n<=2){
cout<<"-1";
}

else if(n%2==0){
	t=n/2;
	a=pow(t,2)-1;
	b=n;
	c=pow(t,2)+1;
	if((pow(a,2)+pow(b,2))==pow(c,2)){
		cout<<a<<" "<<c;
	}
	else{
		cout<<"-1";
	}
}
else{
	a=n;
	b=(pow(n,2)-1)/2; 
	c=(pow(n,2)+1)/2; 
	A=pow(a,2);  
	B=pow(b,2);
	C=pow(c,2);
	if( (A+B)==C ) {
		cout<<b<<" "<<c;
	}
	else{
		cout<<"-1";
	}
}

return 0;

}

Hello @poorva2145,

The logic for even value of n is wrong.
Please, refer to the video Pythagoras Triplet hint.

Let me know if you do not understand anything.

Please tell the error, Iā€™m not able to find it. I have checked the code for many numbers(even as well as odd) and the output is coming right, but it is not passing two test cases.

Sure @poorva2145,

The problem is with the power function.
It does not work for the values, when the result is greater than the range of int.
So, your program is failing for the large inputs.

I have corrected it:

Hope, this would help.

1 Like