如何用Java输出所有四叶玫瑰数
来源:网络收集 点击: 时间:2024-07-12首先,先要了解这个数的要求,这样才能准吐斤叮始确选择使用什么方式、方法甚至算法来求得这个数。四叶玫瑰数,是指一个 四位数 ( n=4),它的每个位上的数字的 n 次幂之和等于它本身。
(例如:1^4 + 6^4+ 3^4 + 4^4= 1634)

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

先写一个函数计算一个数字的四次方为多少。我命名为fours()
private static int fours(int n) {
return n * n * n * n;
}

判断这个数是不是水仙花数,求每一位数上的数的四次方和是否为原数独丽八字本身。
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;
}

写一个for循环来判断那些数字是四叶玫瑰数,并输出。
System.out.println(FourLeafRoses:);
for (int index = 1000; index 10000; ++index) {
if (isFourLeafRoses(index))
System.out.print(index + \t);
}

一定要快快乐乐地学习~~~
注意代码书写规范啊~~
java版权声明:
1、本文系转载,版权归原作者所有,旨在传递信息,不代表看本站的观点和立场。
2、本站仅提供信息发布平台,不承担相关法律责任。
3、若侵犯您的版权或隐私,请联系本站管理员删除。
4、文章链接:http://www.1haoku.cn/art_950814.html