找出小於 100,000 的整數 x,使得:
x + 100 = n²x + 268 = m² (原題 168+100=268)核心考點:數學建模轉化、平方數判斷、枚舉優化。
#include <stdio.h>
#include <math.h>
int main() {
int i, n, m, count = 0, results[100];
for (i = 1; i < 100000; i++) {
n = sqrt(100 + i);
m = sqrt(268 + i);
if (n*n == 100+i && m*m == 268+i) {
results[count++] = i;
}
}
printf("符合條件的數有 %d 個:\n", count);
for (i = 0; i < count; i++) printf("%d\n", results[i]);
return 0;
}
由題意得:
m² - n² = (x+268) - (x+100) = 168 (m-n)(m+n) = 168
設 a = m-n, b = m+n,則:
a × b = 168a, b 同奇偶 (因 m,n 為整數,m+n 和 m-n 同奇偶)b > a > 0m = (a+b)/2, n = (b-a)/2x = n² - 100
#include <stdio.h>
#include <math.h>
int main() {
int target = 168;
int count = 0;
// 枚舉 a 從 1 到 sqrt(168)
for (int a = 1; a * a <= target; a++) {
if (target % a != 0) continue;
int b = target / a;
// a, b 同奇偶
if ((a % 2) != (b % 2)) continue;
int m = (a + b) / 2;
int n = (b - a) / 2;
int x = n * n - 100;
if (x > 0 && x < 100000) {
printf("x = %d (n=%d, m=%d, a=%d, b=%d)\n", x, n, m, a, b);
count++;
}
}
printf("共 %d 個解\n", count);
return 0;
}
| a | b=168/a | 同奇偶? | m | n | x=n²-100 | 有效? |
|---|---|---|---|---|---|---|
| 1 | 168 | 否 (奇/偶) | - | - | - | ✗ |
| 2 | 84 | 是 (偶/偶) | 43 | 41 | 1581 | ✓ |
| 3 | 56 | 否 | - | - | - | ✗ |
| 4 | 42 | 是 | 23 | 19 | 261 | ✓ |
| 6 | 28 | 是 | 17 | 11 | 21 | ✓ |
| 7 | 24 | 否 | - | - | - | ✗ |
| 8 | 21 | 否 | - | - | - | ✗ |
| 12 | 14 | 是 | 13 | 1 | -99 | ✗ (x≤0) |
滿足條件的正整數 x < 100,000 共有 3 個:
| 方法 | 迭代次數 | 時間複雜度 | 核心思想 |
|---|---|---|---|
| 暴力枚舉 x | 100,000 | O(N) | 直接檢查定義 |
| 枚舉 n (√x) | ~316 | O(√N) | n² = x+100 → x = n²-100 |
| 因子分解 (最優) | ~12 | O(√D) (D=差值) | 代數結構 m²-n² = D |