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;
}
}