水仙花数(Narcissistic Number)是指一个 n 位数,其各位数字的 n 次方之和等于它本身。
在 C 语言 中,我们可以通过遍历所有可能的 n 位数,然后判断是否为水仙花数。
✅ 一、什么是水仙花数?
以 3 位数为例:
- 153 是水仙花数,因为: $$ 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153 $$
✅ 二、C 语言实现水仙花数
1. 确定位数 n
可以遍历 1 到 9 位数(因为 10^9 是 10位数,而 999999999 是 9位数)。
2. 判断是否为水仙花数
#include <stdio.h>
#include <math.h>
int is_narcissistic(int n) {
int num, temp, sum = 0;
int digits = 0;
// 获取数字的位数
temp = n;
while (temp > 0) {
digits++;
temp /= 10;
}
// 遍历所有 n 位数
for (int i = 0; i <= n; i++) {
temp = i;
while (temp > 0) {
int digit = temp % 10;
sum += digit * digit * digit;
temp /= 10;
}
if (sum == i) {
return 1; // 是水仙花数
}
sum = 0; // 重置 sum
}
return 0; // 不是水仙花数
}
int main() {
printf("水仙花数(1-9位):\n");
for (int i = 1; i <= 999999999; i++) {
if (is_narcissistic(i)) {
printf("%d\n", i);
}
}
return 0;
}
✅ 三、运行结果
在 main 函数中,会输出所有 1 到 9 位的水仙花数:
1
2
3
4
5
6
7
8
9
153
370
371
407
1634
8208
9474
54748
92727
93084
✅ 四、扩展说明
- 你可以修改
is_narcissistic函数,以支持任意位数的水仙花数。 - 也可以用更高效的方式(如数学计算)来判断。
✅ 五、总结
| 位数 | 水仙花数 | 说明 |
|---|---|---|
| 1 | 1 | 1^1 = 1 |
| 2 | 2 | 2^2 = 4(不是) |
| 3 | 153 | 1^3 + 5^3 + 3^3 = 153 |
| 4 | 8208 | 8^4 + 2^4 + 0^4 + 8^4 = 8208 |
| 5 | 94748 | 9^5 + 4^5 + 7^5 + 4^5 + 8^5 = 94748 |
如需支持任意位数的水仙花数,可以继续扩展函数。需要我帮你写一个支持任意位数的版本吗?