0

I'm on my way of solving euler problem 108, therefore I want to find the integer n so that that there are 1000 combinations of: 1/i + 1/t = 1/n (i and t are random numbers). My code:

int counter = 0;

    for (int n = 10000; n < 200000; n++) {
        for (int i = n; i < 1000000; i++) {
            for (int t = i; t < 1000000; t++) {
                if ((n * (i + t)) == (i * t)) {                     
                    counter++;
                    if (counter == 1000) {
                        System.out.println("Counter: " + counter);
                        System.out.println("N: " + n);
                        System.exit(0);
                    }                       
                }
            }           
        }   
        counter = 0;
    }

However, this does not terminate. How come? I reset the counter for each round and check if it ever reaches the value 1000.

JavaCoder
  • 49
  • 4

1 Answers1

2

Your loop takes too much time to terminate.

You have a considerable number of steps inside each loop, which is computed with multiplication in your time complexity (O(loopIter1*loopIter2*loopIter3)), leading to a considerable matter of time.

As @BorisTheSpider mentioned, your loops will result to 2e17 iterations, which requires a few years (or decades) to terminate - well, it is not suggested to wait that much :)

Consider also that you probably exceed an integer variable beyond its max value. While this might not lead to an overflow or underflow in Java, it can still lead to unexpected behavior, as of after an integer variable reaches Integer.MAX_VALUE (which is 2^32 - 1), an increment will make its value Integer.MIN_VALUE and so on.

In a case of int max value exceeding as described above, some checks may fail: think that Integer.MAX_VALUE > 1000, but Integer.MAX_VALUE + 1 will lead to Integer.MIN_VALUE < 1000.

In your code it does not seem to affect it direcly, but I would seriously consider this effect in your computations.

Community
  • 1
  • 1
Nick Louloudakis
  • 5,856
  • 4
  • 41
  • 54
  • What kind of adjustments are then needed? I cannot understand how I can make this code more efficient considering that it basically only consists of there for-loops. – JavaCoder Mar 12 '16 at 16:45
  • 2
    @JavaCoder Project Euler challenges are **always** about understanding the underlying mathematics and not brute force. In fact, they are specifically _designed_ to not be brute-forceable. – Boris the Spider Mar 12 '16 at 20:12