1

Today I practiced for my coding test using projecteulers problems. While doing the prime factor division I stumbled across something I found weird. Here is the relevant code (res is an ArrayList):

for (int x = 2; x <= n; x++){       
    if (n % x == 0){
        System.out.println("Prime found: " + x);
        res.add(x);
        n = n / x;
    }       
}

Which divided 1000 into [2, 4, 5, 25]. After a while I tried replacing the if-statement with a while-loop and it printed me the correct answer [2, 2, 2, 5, 5, 5].

Obviously there is somthing I didn't understand, could someone explain this to me, please?

Edit:

The newer code:

for (int x = 2; x <= n; x++){       
    while (n % x == 0){
        System.out.println("Prime found: " + x);
        res.add(x);
        n = n / x;
    }       
}
f-CJ
  • 4,235
  • 2
  • 30
  • 28
GabbaGandalf
  • 119
  • 7

2 Answers2

3

The difference is:

  • If you use if, every number is tested only once. So if you are able to pull out the 2, you try so only once. The next number you can pull out is the 4, although it is not a prime. The same holds for the 5 resp. 25.
  • If you use while, you test each number until you know it's no longer in the number to test.
glglgl
  • 89,107
  • 13
  • 149
  • 217
1

You could also change it into

for (int x = 2 ; x <= n/x ; ) {       
        if (n % x == 0) {
            System.out.println("Prime factor: " + x);
            res.add(x);
            n = n / x;
        }       
        else {
            x++;         // increment moved here
        }
    }
if (n > 1) {
    System.out.println("Prime factor: " + n);
    res.add(n);
}

I've also changed the termination condition, to make it much more efficient in cases where n's largest prime factor is itself large, because if n = a*b and a <= b, then a*a <= a*b = n, i.e. a <= n/a.

This repeats the test for a prime factor, because as you've found out, some numbers have multiple prime factors of same magnitude (like 1000 = 2*2*2*5*5*5). It is equivalent to your while loop, because the increment is now conditional, performed only when the tested candidate was not n's factor.

Will Ness
  • 70,110
  • 9
  • 98
  • 181