Java – all natural numbers, the sum is n, and the reverse sum is 1

I have a problem to solve N natural numbers are given I need to find a list of natural numbers, sum to a given number, and reverse to 1

a + b + c + ... = N
1/a + 1/b + 1/c + ... = 1

a. B and C are not necessarily unique

I have proposed the following code in Java It is suitable for simple cases, but it is very slow for n > one thousand

How to rewrite this method, even if millions of work fast? Maybe I should give up recursion, or cut off some branches with the mathematical skills I miss?

SSCEE:

private final static double ONE = 1.00000001;

public List<Integer> search (int number) {
    int bound = (int)Math.sqrt(number) + 1;
    List<Integer> list = new ArrayList<Integer>(bound);

    if (number == 1) {
        list.add(1);
        return list;
    }

    for (int i = 2; i <= bound; i++) {
        list.clear();
        if (simulate(number,i,list,0.0)) break;
    }

    return list;
}


//TODO: how to reuse already calculated results?
private boolean search (int number,int n,List<Integer> list,double sum) {
    if (sum > ONE) {
        return false;
    }

    //would be larger anyway
    double minSum = sum + 1.0 / number;
    if (minSum > ONE) {
        return false;
    }

    if (n == 1) {
        if (minSum < 0.99999999) {
            return false;
        }

        list.add(number);
        return true;
    }

    boolean success = false;
    for (int i = 2; i < number; i++) {
        if (number - i > 0) {
            double tmpSum = sum + 1.0 / i;
            if (tmpSum > ONE) continue;

            list.add(i);
            success = search(number - i,n - 1,tmpSum);
            if (!success) {
                list.remove(list.size() - 1);
            }

            if (success) break;
        }
    }

    return success;
}

Solution

The paper "a theory on partitions", 1963 by Graham, R. L. shows that there is a solution for n > 77, in which the number used is dinstinct, and an algorithm is proposed to find such decomposition

The algorithm is as follows:

>If n is less than 333, the pre calculation table is used to obtain the results. > If n is an odd number, (n-179) / 2, find the decomposition D1, D2, D3, D4,..., DK, then 3,7,78,91,2 * d1,2 * d2,2 * d3,2 * DK is the decomposition of N > if n is an even number, (n-2) / 2, find the decomposition D1, and then find that 2,2 * DK is the decomposition of n

However, since you do not care about having different numbers in the decomposition, you can reduce the size of the table of pre calculation results to 60, and find the decomposition D1, (N-9) / 2 when n is an odd number, then 3,6,2 * DK is the decomposition of n

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>