水仙花数只是自幂数的一种,严格来说3位数的3次幂数才称为水仙花数。
附:其他位数的自幂数名字
一位自幂数:独身数
两位自幂数:没有
三位自幂数:水仙花数
四位自幂数:四叶玫瑰数
五位自幂数:五角星数
六位自幂数:六合数
七位自幂数:北斗七星数
八位自幂数:八仙数
九位自幂数:九九重阳数
十位自幂数:十全十美数
这里我们给出代码求1-9位数字中所有的花数
public class Main {
public static void main(String[] args) {
System.out.println("水仙花数有:");
for (int i = 0; i < 999999999; i++) {
int temp = i;
int count = 0;
//先判断i的位数
while (temp != 0){
temp /= 10;
count++;
}
//判断是否是水仙花数
temp = i;
int sum = 0;
for (int j = 0; j < count; j++) {
int a = temp%10;
sum += Math.pow(a,count);
temp /= 10;
}
if(sum == i){
System.out.println(i);
}
}
}
}
由于计算量非常大,程序运行一段时间后才出最终结果
水仙花数有:
0
1
2
3
4
5
6
7
8
9
153
370
371
407
1634
8208
9474
54748
92727
93084
548834
1741725
4210818
9800817
9926315
24678050
24678051
88593477
146511208
472335975
534494836
912985153
Process finished with exit code 0