What kind of formula required in calculating pythagoras triplet if any one length is given
Pythagoras Triplet
You can use the following approach:
- If n<0, n=1, n=2. Print -1 and return because squares aren’t possible for these numbers.
- Now if n is even. We will simplify the Pythagorean equation.
a^2 + b^2 = c^2. Hence we manipulate the equation as a^2 = (c+b)(c-b). Now if the given number is even i.e. a is even, we can express it as product of 2 even numbers say 2 and (a^2)/2.
(a^2)/2 * 2 = (c-b)(c+b)
Hence c+b = 2 and c-b = (a^2)/2. Now solve for b and c and do similarly if given n is odd. (NOTE: I have taken a = n)
Also, when the complexity and calculations are huge in any problem. There’s usually a simple equation behind that, you can also try to deduce that in questions of such type.
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.
This is my code Scanner scn = new Scanner (System.in); int n= scn.nextInt(); int b,c,count=0,counter=0; if(n>2){ //finding the number if(n%2==0){ c= nn/4 + 1; b= nn/4 -1; }else{ c=(nn + 1)/2; b=(nn - 1)/2; } // finding greater if(b>c){ count=1; counter=1; } // finding greatest among all if(count==1){ if(n>c){ count=2; }else{ count=3; } }else{ if(n>c){ count=4; }else{ count=5; } } switch(count){ case 2: if(nn==bb + cc){ if(b>c) System.out.print(c + " " + b); else System.out.print(b + " " + c); } case 3: if(cc==bb + nn){ System.out.print(b + " " + c); } case 4: if(nn==bb + cc){ if(b>c) System.out.print(c + " " + b); else System.out.print(b + " " + c); } case 5: if(cc==bb + nn){ System.out.print(b + " " + c); } //default : // System.out.print(“hello”); } }else{ System.out.print("-1"); } not able to find out the problem why 2 test cases are not satisfied
@shubhamkumarsingh,
I have corrected your code. https://ide.codingblocks.com/s/184205.
You were unnecessarily complicating the code. You don’t need to use switch or check if b>c. (n* n)/4 + 1 is always greater than (n* n)/4 - 1 under the given constraints on inputs.
Also next time for code sharing please use https://ide.codingblocks.com/
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.