Project Euler #7: What is the 10,001st prime number? By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can
  see that the 6th prime is 13.
  
  What is the 10 001st prime number?


How can I make this more efficient and cleaner?

public class Problem7 {

    public static void main(String[] args) {
        // a prime factor is something that can divide by only 1 and itself evenly
        int counter = 0;
        int primeNum = 0;

        for (int num = 2; num &lt; 10000000; num++) {
            boolean isPrime = true;
            for (int factor = 2; factor &lt; num; factor++) {

                if (num % factor == 0) {
                    isPrime = false;
                    break;
                }
            }
            if (isPrime) {
                primeNum = num;
                counter++;
            }
            if (counter == 10001) {
                break;
            }
        }
        System.out.println(primeNum);
    }
}
More efficient... look at Sieve of Eratosthenes for a huge speed up. I'm ignoring it for now, as it comes again and again.

for (int num = 2; num &lt; 10000000; num++) {


The condition num &lt; 10000000 is plain wrong. It works, but makes no sense. If the requirements change, the limit may be too small. Just drop it. Or better, replace it by counter &lt; 10001 (nobody says, that you have to test num, any condition is allowed).

You surely know that 4, 6, 8, ... are no primes, so you can skip them. Iterate over odd numbers only and set the initial value of counter equal to one (accounting for the skipped prime 2). So you get something like

for (int num = 3; counter &lt; 10001; num += 2) {




This hardly helped the speed, but doing the same thing in

for (int factor = 2; factor &lt; num; factor++) {


surely helps. You only have to deal with odd num, so you test only odd factors.



Observe that for each factor, also num / factor is a factor and the smaller of the two is no bigger than the square root of num. So you can use

int limit = (int) Math.sqrt(num);
for (int factor = 3; factor &lt;= limit; factor += 2) {




        if (isPrime) {
            primeNum = num;
            counter++;
        }


This looks a bit strange. It works, but you assign primeNum just in case it'll be needed. A rather useless variable as num would do, too.



Even for such a rather trivial tasks you should use methods. Write small methods and let each of them do just one thing. Especially, never mix user input or output with computation as this makes the code perfectly non-reusable. Try to write methods like

boolean isPrime(int num);
int nextPrimeAbove(int num);
int nthPrime(int n);