https://online.codingblocks.com/player/7545/content/5167?s=1435
Can i get hits for pythagros triplet que
Hey Ankush, what exact issue are you facing with this question. In this problem, you will be given a number n and you just have to print its Pythagoras pair in increasing order if they exist, otherwise you are supposed to print ā-1ā. If you are facing some problem with the code then share the link of your code we will help you in debugging the code.
my loop is running infinite times
Hey Ankush, your logic is not correct, as you are iterating in the for loop till infinity
for(int i = m + 1; i <= INT_MAX; i++ ), if a no.'s Pythagoras triplets doesnāt exist then your codeās loop will never break, and run infinite times.
can i get more hints for logic or is my code is near the logic pls tell
Hey Ankush, here I am sharing the approach for this problem
-
If m>n>0 are integers, then (m2-n2, 2mn, m2-n2) is a Pythagorean triple. This is easily seen with a bit of algebra. Thus, plugging in various (m,n) will give various triples.
-
Now, our goal is to find a triple of the form (m2-n2, 2mn, m2-n2) in which our input value is one of the catheti. Note that the catheti are m2-n2 and 2mn. Also, note that the second cathetus is always even. Thus, it makes sense to consider two cases:
-
If a is even, then letās try to equate it with the second cathetus, 2mn, i.e., letās try to find an (m,n) pair such that 2mn = a. In this case, is even, so we can divide by 2. We have mn = a/2. Thus, all we have to do is to find a factorization of a/2 into mn such that m>n. You can try various factoring methods ā even naĆÆve O(āa) time method will pass - but in this case , we donāt really even need to do that, since the trivial (m,n) = (a/2,1) works!. This gives us the solution triple ( (a^2)/4 - 1, a, (a^2)/4 + 1 ). Note that (a^2)/4 is an integer since a is even.
-
If a is odd, then we canāt equate it with the second cathetus, so letās try instead m2-n2, i.e. we want to find an (m,n) such that m2-n2 = a. Node that m2-n2 = (m+n)(m-n), so all boils down again to factoring! Letās try our trivial factorization again: (m+n, m-n) = (a,1) What we get is a system of two linear equations: m+n=a and m-n=1 which has solution m=(a+1)/2 and n=(a-1)/2. Substituting back, this gives us the triple (a, (a^2 - 1)/2, (a^2 + 1)/2). Note that (a^2 + 1)/2 is an integer as a is odd.