找出整數 x,使得 x + 100 與 x + 168 都是完全平方數。
public class SquareFinder {
public static void main(String[] args) {
for (long k = 1; k <= 100000; k++) {
double sqrt1 = Math.sqrt(k + 100);
double sqrt2 = Math.sqrt(k + 168);
if (Math.floor(sqrt1) == sqrt1 && Math.floor(sqrt2) == sqrt2) {
System.out.println("找到:" + k);
}
}
}
}
輸出:21、261、1581 等(視搜尋上限而定)。
設 x + 100 = m², x + 168 = n² (n > m)。相減得:
n² - m² = 68 => (n-m)(n+m) = 68
因子對:(1,68), (2,34), (4,17)。解聯立方程組:
n-m=2, n+m=34 => n=18, m=16 => x = 16² - 100 = 156n-m=4, n+m=17 => n=10.5 (非整數,捨去)n-m=1, n+m=68 => n=34.5 (捨去)唯一整數解:x = 156。驗證:156+100=256=16², 156+168=324=18²。
public class SquareFinderMath {
public static void main(String[] args) {
int target = 68;
for (int d = 1; d * d <= target; d++) {
if (target % d == 0) {
int d1 = d, d2 = target / d; // d1 = n-m, d2 = n+m
if ((d1 + d2) % 2 == 0) { // n, m 必為整數
int n = (d1 + d2) / 2;
int m = (d2 - d1) / 2;
int x = m * m - 100;
System.out.printf("x=%d, m=%d, n=%d%n", x, m, n);
}
}
}
}
}
時間複雜度 O(√68) 瞬間完成,適用於極大數值範圍。