水仙花數是指一個 n 位數(n ≥ 3),其各位數字的 n 次冪之和等於該數本身。例如:153 = 1³ + 5³ + 3³。
#include <stdio.h>
#include <math.h>
int isNarcissistic(int num) {
int original = num;
int n = 0;
int temp = num;
// 計算位數
while (temp > 0) {
n++;
temp /= 10;
}
// 位數 < 3 直接返回 false
if (n < 3) return 0;
int sum = 0;
temp = num;
while (temp > 0) {
int digit = temp % 10;
sum += (int)pow(digit, n);
temp /= 10;
}
return sum == original;
}
int main() {
printf("10000 以內的水仙花數:\n");
for (int i = 100; i < 10000; i++) {
if (isNarcissistic(i)) {
printf("%d ", i);
}
}
printf("\n");
return 0;
}
10000 以內的水仙花數:
153 370 371 407 1634 8208 9474
pow()。參考百度知道解法:鏈接(將 1000 改為 10000 即可)。