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

 时间:2026-02-14 16:11:56

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输出所有四叶玫瑰数

  • C语言中的函数如何声明和使用?
  • 怎样用C++输出 hello world?
  • strcpy函数怎么用
  • c++怎样读文件?
  • C语言的链表如何对某个位置进行元素的插入
  • 热门搜索
    梦幻西游化生寺怎么加点 ppt怎么加背景图片 阿兰若梦境是怎么回事 反应蛋白高怎么回事 怎么做照片 笔记本怎么连接电视 萝卜干怎么做 衣服褪色怎么办 动态心电图怎么做 路由器网关怎么设置