一个N位的十进制正整数,如果它的每个位上的数字的N次方的和等于这个数本身,则称其为花朵数。
例如:
当N=3时,153就满足条件,因为 1^3 + 5^3 + 3^3 = 153,这样的数字也被称为水仙花数(其中,“^”表示乘方,5^3表示5的3次方,也就是立方)。
当N=4时,1634满足条件,因为 1^4 + 6^4 + 3^4 + 4^4 = 1634。
当N=5时,92727满足条件。
实际上,对N的每个取值,可能有多个数字满足条件。
程序的任务是:求N=21时,所有满足条件的花朵数。注意:这个整数有21位,它的各个位数字的21次方之和正好等于这个数本身。
如果满足条件的数字不只有一个,请从小到大输出所有符合条件的数字,每个数字占一行。因为这个数字很大,请注意解法时间上的可行性。
代码:
package BigTitle;
import java.math.BigInteger;
import java.util.Arrays;
public class FlowerNum
{
private static BigInteger[] table = new BigInteger[10];
public static void main(String[] args)
{
long time = System.nanoTime();
find(21);
time = System.nanoTime() - time;
System.out.println(time / 1000000000.0 + "s");
}
public static void find(int n)
{
for (int i = 0; i < 10; i++)
table[i] = BigInteger.valueOf(i).pow(n);
int[] nums = new int[n];// 记录21位数字
int index = 0; // index表示指向21位数的第几位
int num = 0; // num指示当前位上的数字
BigInteger sum = BigInteger.ZERO;
BigInteger MIN = BigInteger.TEN.pow(n - 1);// 所求数字最小不小于20位数
BigInteger MAX = BigInteger.TEN.pow(n).subtract(BigInteger.ONE);// 最大不大于10的21次方
while (true)
{
if (index < nums.length && num < 10)
{ // 如果没遍历完且当前数字不大于10,设置21位数的组合情况
BigInteger temp = sum.add(table[num]); // 记录当前的值
if (temp.compareTo(MAX) < 0)
{// 如果比最大值小,则继续处理
nums[index] = num;
index++;
sum = temp;
continue;
}
}
else if (index >= nums.length && sum.compareTo(MIN) > 0)
{// 21位数全部设置完且不小于最小
int[] temp = getArray(sum);
if (check(nums, true, temp, false))
System.out.println(sum);
}
else if (index <= 0)
{ // 表示遍历完了
break;
}
index--;
num = nums[index];
sum = sum.subtract(table[num]);// 减法
num++;
}
}
public static boolean check(int[] a1, boolean copy1, int[] a2, boolean copy2)
{
if (a1.length != a2.length)
return false;
if (copy1)
a1 = a1.clone();
if (copy2)
a2 = a2.clone();
Arrays.sort(a1);
Arrays.sort(a2);
return Arrays.equals(a1, a2);
}
public static int[] getArray(BigInteger big)
{
String s = String.valueOf(big);
int length = s.length();
int[] res = new int[length];
for (int i = 0; i < length; i++)
res[i] = s.charAt(i) - '0';
return res;
}
}