Sir/Maam
What could the approach to this problem ?
Pythagoras Triplet query
Pythagorean triplet are of form m^2-n^2, 2mn , m^2+n^2…in this ques you are given a value…assume that this value can be of first form or second form(as it is given in the ques that the value is one of the leg of the triangle)…so if the given value say ‘a’ is even then you can equate it to 2mn…mn=a/2…there can be various values of (m,n)…you can take any value of (m,n)… one possible value can be m=a/2 and n=1…else if the given value ‘a’ is odd equate it to m^2-n^2…by factorization m^2-n^2=(m+n)(m-n)…(m+n)(m-n)=a…there could be many values of (m,n)…you can chose any one…(m+n)=a and (m-n)=1 solving these two equations we get m=(a+1)/2 and n=(a-1)/2…as you know the values of m,n rest of the two pythagorean triplets can be found…
Sir what changes are required in this code :
Scanner obj = new Scanner(System.in); int a = obj.nextInt(); if(a<=Math.pow(10,9)){ int m, n, h, s; if(a%2==0){ for(m=2; m<a; m+=1){ for(n=1; n<m; n+=1){ if(a==(2mn)){ h = mm + nn; s = mm - nn; System.out.println(s+" “+h); break; } } } }else{ for(m=2; m<a; m+=1){ for(n=1; n<m; n+=1){ if((mm-nn)==a){ h = mm + nn; s = 2mn; System.out.println(s+” "+h); break; } } } } }
if(a<=Math.pow(10,9)){ int m, n, h, s; if(a%2==0){ for(m=2; m<a; m+=1){ for(n=1; n<m; n+=1){ if(a==(2mn)){ h = mm + nn; s = mm - nn; System.out.println(s+" “+h); break; } } } }else{ for(m=2; m<a; m+=1){ for(n=1; n<m; n+=1){ if((mm-nn)==a){ h = mm + nn; s = 2mn; System.out.println(s+” "+h); break; } } } } }
see if we have to write a^2 we dont write as aa we write as a*a
moreover your logic is fine but it will give tle due to for loops…just do the ques as i have stated in comments…it will give ans in constant time
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.