找出所有四位整數 abcd(即 1000~9999),滿足 (ab + cd)² = abcd,其中 ab 為高兩位,cd 為低兩位。按從小到大輸出,每行一個。
#includeint main() { for (int i = 1000; i < 10000; ++i) { int ab = i / 100; // 高兩位 int cd = i % 100; // 低兩位 int sum = ab + cd; if (sum * sum == i) { printf("%d\n", i); } } return 0; }
2025 3025 9801
驗證:
2025 → 20+25=45, 45²=2025 ✓
3025 → 30+25=55, 55²=3025 ✓
9801 → 98+01=99, 99²=9801 ✓
設 S = ab + cd,則 S² = 100·ab + cd。
因 0 ≤ ab, cd ≤ 99,故 0 ≤ S ≤ 198。
但 S² 為四位數 → 32 ≤ S ≤ 99(因 31²=961 三位,100²=10000 五位)。
只需枚舉 S = 32..99,計算 S²,再驗證 ab+cd == S:
for (int S = 32; S <= 99; ++S) {
int sq = S * S;
int ab = sq / 100;
int cd = sq % 100;
if (ab + cd == S) printf("%d\n", sq);
}
僅 68 次迴圈,極致優化。
// 字串法(簡單)
char s[5]; scanf("%4s", s);
for (int i = 3; i >= 0; --i) putchar(s[i]);
// 數學法(無緩衝區)
int n; scanf("%d", &n);
while (n) { putchar('0' + n%10); n/=10; }
int n, sum = 0; scanf("%d", &n);
while (n) { sum += n % 10; n /= 10; }
printf("%d\n", sum);
/100 取高兩位、%100 取低兩位、S² 範圍推導。