I have a problem to solve. N
natural number is given. I need to find a list of natural numbers which sum up to that given number and at the same time the inverses up to 1.
a + b + c + ... = N
1/a + 1/b + 1/c + ... = 1
a
, b
, c
don't have to be unique.
I have come up with following code in Java. It works for simple cases, but incredibly slow for already for N > 1000
.
How can I rewrite the method so it works fast even for millions? Maybe, I should drop off recursion or cut off some of branches with mathematical trick which 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, list, tmpSum);
if (!success) {
list.remove(list.size() - 1);
}
if (success) break;
}
}
return success;
}