阿姆斯壯數又稱自戀數,指一個 n 位數,其各位數字的 n 次方之和等於該數本身。對於三位數 abc,滿足條件:a³ + b³ + c³ = abc。
輸入一個三位整數,判斷是否為阿姆斯壯數。若輸入非三位數,提示錯誤。
#include <stdio.h>
int main() {
int num, a, b, c;
printf("請輸入一個三位數: ");
scanf("%d", &num);
if (num < 100 || num > 999) {
printf("%d 不是三位數,輸入有誤!\n", num);
} else {
a = num % 10; // 個位
b = num / 10 % 10; // 十位
c = num / 100; // 百位
if (a*a*a + b*b*b + c*c*c == num) {
printf("%d is Armstrong.\n", num);
} else {
printf("%d is not Armstrong!\n", num);
}
}
return 0;
}
輸入: 153 輸出: 153 is Armstrong. 驗證:1³ + 5³ + 3³ = 1 + 125 + 27 = 153 ✓ 輸入: 123 輸出: 123 is not Armstrong! 驗證:1³ + 2³ + 3³ = 1 + 8 + 27 = 36 ≠ 123 輸入: 99 輸出: 99 不是三位數,輸入有誤!
只有四個三位數符合條件:
若要找出所有 n 位數的阿姆斯壯數,可參考下一篇文章(問題七十八)的遍歷法。通用解法需動態計算位數 n,並對每位進行 n 次方運算。