java代码实现求取水仙花数

水仙花数(Narcissistic number)也被称为超完全数字不变数(pluperfect digital invariant, PPDI)、自恋数、自幂数、阿姆斯壮数或阿姆斯特朗数(Armstrong number),水仙花数是指一个 3 位数,它的每个位上的数字的 3次幂之和等于它本身。

方法一:

package shuixianhuanumber;

public class ShuiXianHua {
    public static void main(String[] args) {
        for(int i =100;i<1000;i++){     //水仙花数是三位数,故i取值100~999
            int a = i/100;      //求取百位数
            int b = i%100/10;   //求取十位数
            int c = i%10;       //求取个位数
            int temp = a*a*a+b*b*b+c*c*c;
            /*如果temp==i,则该数是水仙花数.*/
            if(temp==i){
                System.out.println(i);  //打印水仙花数
            }
        }
    }
}
//结果:
153
370
371
407

方法二:

package shuixianhuanumber;

public class ShuiXianHua {
    public static void main(String[] args) {
        int i =100;
        while (i<1000){
            if (i==(Math.pow((int)(i/100),3)+Math.pow((int)(i%100/10),3)+Math.pow(i%10,3))){       //用Math.pow求取立方
                System.out.println(i);  //打印水仙花数
            }
            i++;
        }
    }
}
//结果:
153
370
371
407

更多推荐

水仙花数JAVA代码实现