I want to find the integer, n, so that there are 1000 combinations when 1/z + 1/x = 1/n. This is my code:
int counter = 0;
double n = 1;
while (true) {
for (double i = 1; i < 10000; i++) {
for (double t = 1; t < 10000; t++) {
if ((1/i) + (1/t) == (1/n)) {
counter++;
System.out.println(counter);
}
}
}
if (counter < 1000) {
counter = 0;
n++;
} else {
System.out.println("Counterr: " + counter);
System.out.println("Answer: " + n);
System.exit(0);
}
}
It works if I try to find 4 combinations, but not when 1000. Why?
That's probably because of floating point precision issues. You use increment ++
operator on double within a loop and compare doubles by ==
. Result of those operations may be not as expected, especially after many iterations.
Try changing your code to work with integers with exact precision, not doubles. Note that your equation
1/z + 1/x = 1/n
is equivalent to
n * (x + z) = x * z
So, change your loop as follows:
for (int i = 1; i < 10000; i++) {
for (int t = 1; t < 10000; t++) {
if (n * (i + t) == i * t) {
counter++;
System.out.println(counter);
}
}
}
Also, there is now more clear how to optimize your iteration ranges. Think about lower and upper limits for i
and t
- reducing iteration ranges will improve overall performance significantly.
Unfortunately, I didn't tested the result at the moment, but I'm pretty sure you should do calculations in integers, not in doubles.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments