如何用Java输出所有四叶玫瑰数

2025-11-07 06:48:38

1、首先,先要了解这个数的要求,这样才能准确选择使用什么方式、方法甚至算法来求得这个数。四叶玫瑰数,是指一个 四位数 ( n=4),它的每个位上的数字的 n 次幂之和等于它本身。

(例如:1^4 + 6^4+ 3^4 + 4^4= 1634)

如何用Java输出所有四叶玫瑰数

2、创建工程,或使用已有工程,在工程下创建包,包内新建一个类,我命名为FourLeafRoses类,大家根据自己喜好随便命名,但请保持类名与文件名一致。

如何用Java输出所有四叶玫瑰数

3、先写一个函数计算一个数字的四次方为多少。我命名为fours()

private static int fours(int n) {

  return n * n * n * n;

}

如何用Java输出所有四叶玫瑰数

4、判断这个数是不是水仙花数,求每一位数上的数的四次方和是否为原数字本身。

private static Boolean isFourLeafRoses(int number) {

  int thousands = number / 1000;

  int hundreds = number / 100 - thousands * 10;

  int tens = number / 10 - hundreds * 10 - thousands * 100;

  int ones = number % 10;

  return fours(thousands) + fours(hundreds) 

        + fours(tens) + fours(ones) == number;

}

如何用Java输出所有四叶玫瑰数

5、写一个for循环来判断那些数字是四叶玫瑰数,并输出。

System.out.println("FourLeafRoses:");

for (int index = 1000; index < 10000; ++index) {

  if (isFourLeafRoses(index))

    System.out.print(index + "\t");

}

如何用Java输出所有四叶玫瑰数

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢