四位数各位上的数字的四次方之和等于本身为四叶玫瑰数。
package com.pro.one;
public class RoseNarcissisticNUM {
private static float powerEnd;
private static int count = 0;
public static void main(String[] args) {
for (int i = 1000; i < 9999; i++) {
powerEnd = 0;
String stringed = String.valueOf(i);
String[] splited = stringed.split("");
for (int j = 0; j < splited.length; j++) {
powerEnd += new RoseNarcissisticNUM().powers(Float.parseFloat(splited[j]), 4);
if (powerEnd==i&&j==splited.length-1) { //防止出现四个数字还没有加完就判等了
count++;
System.out.println("第 "+count+" 个四叶玫瑰数: "+i);
}
}
}
}
private float powers(float base, float pow) {
if (pow>0) {
return base*powers(base, pow-1);
}else if (pow<0) {
return 1/(base*powers(base, -pow-1)); //如果取int,则倒数的次幂会约为0
}else {
return 1;
}
}
}
//Result:
第 1 个四叶玫瑰数: 1634
第 2 个四叶玫瑰数: 8208
第 3 个四叶玫瑰数: 9474