100——1000之间的水仙花数?并统计有多少个水仙花数?
水仙花数的概念
所谓的水仙花数是指一个三位数,其各位数字的立方和等于该数本身。
举例:153就是一个水仙花数。
153 = 1*1*1 + 5*5*5 + 3*3*3
计算100——1000之间的水仙花数?并统计有多少个水仙花数?
/*
计算100——1000之间的水仙花数?并统计有多少个水仙花数?
*/
public class OptWhileDemo1 {
public static void main(String[] args) {
int i = 100;
int num = 0;//用于计数
while (i < 1000) {
int g = i % 10;
int s = i / 10 % 10;
int b = i / 100 % 10;
if (i == (Math.pow(g, 3) + Math.pow(s, 3) + Math.pow(b, 3))) {
System.out.print(i + "\t");
num++;//找到水仙花数自加1
}
i++;
}
System.out.println();
System.out.println("100-1000之间的水仙花数有" + num + "个");
}
}
运行截图: