概述
在数论中,水仙花数(Narcissistic number),也被称为超完全数字不变数(pluperfect digital invariant, PPDI)、自恋数、自幂数、阿姆斯壮数或阿姆斯特朗数(Armstrong number) ,用来描述一个N位非负整数,其各位数字的N次方和等于该数本身。(百度百科)
说明白点,水仙花数就是数字,其的各位数字的立方和等于这个三位数本身。
举个例子:
153 = 1^3 + 5^3 + 3^3。
370 = 3^3 + 7^3 + 0^3。
371 = 3^3 + 7^3 + 1^3。
407 = 4^3 + 0^3 + 7^3。
注意:要判断一个三位数是不是水仙花数,得先取得这个三位数的的个位,十位和百位
for循环法:
public class 水仙花数 {
public static void main(String[] args) {
int sum = 0; //定义一个累加数
for(int i=100;i<=1000;i++){ //设定水仙花数范围
int b = i/100; //取得百位
int s = (i-100*b)/10; //取得十位
int g = (i-s*10-b*100); //取得个位
if(i==g*g*g+s*s*s+b*b*b){ //进行水仙花数判定,注意,^3是行不通的,不匹配
System.out.print(i+" "); //输出范围内所有的水仙花数
sum++;//并计算其个数之和
}
}
System.out.println('\t');
System.out.println("总共有"+sum+"个水仙花数"); //输出水仙花数的总数
}
}
while循环:
/**
* while循环
*/
public class 水仙花数 {
public static void main(String args[]) {
int i = 100;// 水仙花数大于100
int sum = 0; // 用来统计个数
while (i <= 1000) {
int h = i / 100; // 取得百位数
int t = (i - 100 * h) / 10; // 取得十位数
int c = (i - h * 100 - t * 10); // 取得个位数
if (i == c * c * c + h * h * h + t * t * t) { // 水仙花数判定
System.out.print(i + " "); // 输出水仙花数
sum++;
}
i++;
}
System.out.println();
System.out.println("总共有" + sum + "水仙花数个"); // 输出水仙花数的总数
}
}
另外还有do---while法,读者有兴趣可以自行编程。
输出结果: