java 计算 水仙花 花朵数 算法 优化

来源:互联网 发布:消失的夫妻笔录 知乎 编辑:程序博客网 时间:2024/05/11 18:00
import java.math.BigInteger;

public class Flower {
    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);// 计算1-9的n次方,存入table[]
        int[] nums = new int[n];
        int index = 0;
        int num = 0;
        BigInteger sum = BigInteger.ZERO;// 0
        BigInteger MIN = BigInteger.TEN.pow(n - 1);// 10^20
        BigInteger MAX = BigInteger.TEN.pow(n).subtract(BigInteger.ONE);// 10^21-1
        while (true) {
//            System.out.println("sum" + sum + " " + nums[0] + nums[1] + nums[2]
//                    + " index:" + index + " num:" + num);
            if (index < nums.length && num < 10) {

                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) {
                // System.out.println("sum" + sum + " " + nums[0] + nums[1] +
                // nums[2]
                // + " index:" + index + " num:" + num+"*********************");

                int[] temp = getArray(sum);// sum转化为temp数组
                if (check(nums, temp))// 检测sum与nums是否排序后依然相同
                    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, int[] a2) {
        if (a1.length != a2.length)
            return false;
        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;
    }
}
原创粉丝点击