毕达哥拉斯三元组求解程序异常排查:输入408时输出结果不符合预期
Great question—let's break down exactly what's happening with your code and the input n=408.
First, let's confirm: both triplets are valid! 102² + 136² = 170² (and their sum is 408), and 119² + 120² = 169² (sum is also 408). The issue isn't that your formula is wrong—it's that your program's loop logic and assumptions are limiting which triplet it finds first (and stopping early).
1. Your program stops at the first valid triplet it finds
Your loop iterates i starting from 1, and as soon as it hits a valid combination of j and k, it prints the triplet, increments count, and hits break—immediately halting the loop.
For n=408:
- When
i=102, the math checks out:j = (408² - 2*408*102)/(2*408 - 2*102) = 136, andk=408-102-136=170. Since this is a valid triplet, the program prints it and stops. - The triplet you expect (119, 120, 169) would be found when
i=119, but the loop never gets there because of the earlybreak.
2. Your code assumes there's only one valid triplet per n
The final check if (count != 1) { System.out.println("Impossible"); } is incorrect. Some values of n can have multiple distinct Pythagorean triplets that sum to them.
In this case:
- 102,136,170 is a scaled version of the classic primitive triplet 3,4,5 (scaled by 34—since 3+4+5=12, and 12*34=408).
- 119,120,169 is a primitive triplet (its three numbers share no common divisor other than 1) whose sum also equals 408.
How to fix this
If you want to find all valid triplets for a given n:
- Remove the
breakstatement inside theifblock so the loop continues checking all possibleivalues. - Adjust the final check to handle cases where zero or multiple triplets exist (e.g., print "No triplets found" if
count=0, or note how many triplets were found ifcount>1). - You can also optimize the loop by setting
i <= n/3—since for a valid triplet wherei < j < k,ican't be larger than a third ofn(otherwisei+j+kwould exceedn).
Here's a modified version of your code that finds all triplets:
public static void pythagoreanTriplet(int n) { int i, j, k, count = 0; // Optimize loop to avoid unnecessary iterations for (i = 1; i <= n / 3; i++) { j = (n * n - 2 * n * i) / (2 * n - 2 * i); k = n - i - j; if ((i * i + j * j == k * k) && j > 0 && k > 0) { System.out.println(i + " " + j + " " + k); count++; // No break here—keep looking for more triplets } } if (count == 0) { System.out.println("Impossible"); } else if (count > 1) { System.out.println("Found " + count + " valid triplets"); } }
Running this with n=408 will output both triplets you're interested in.
If you only want primitive triplets, add a check to verify that the greatest common divisor (gcd) of i, j, and k is 1. You can write a helper function to compute the gcd of three numbers (compute gcd(i,j), then gcd of that result with k).
内容的提问来源于stack exchange,提问作者parsa.ni

