您的位置:首页 > 编程语言 > Java开发

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

2011-12-09 17:01 253 查看
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
;

        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;

    }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息