Project Euler #7 10001st prime in C++ 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 optimize this code?

#include &lt;iostream&gt;

bool is_prime(int num)
{
    for (int i = 2; i &lt;= num/2; ++i)
    {
        if (num % i == 0)
        {
            return false;
        }
    }
    return true;
}

int main()
{
    int count = 2;
    for (int i = 5; ; i = i+2)
    {
        if (is_prime(i))
        {
            count++;
        }
        if (count == 10001)
        {
            std::cout &lt;&lt; i;
            return 0;
        }
    }
}
Use better algorithms: Sieve_of_Eratosthenes

You used a brute force algorithm. But even this can be highly improved.

You increment by 2 each loop.

    for (int i = 5; ; i = i+2) {


So you have noticed that all even numbers are not prime. You can improve on this. By incrementing by 2 then 4 then 2 then 4. This removes all multiples of 2 and 3 automatically.

    int inc = 2;
    for (int i = 5; ; i += inc, inc = 6 - inc) {


The brute force check runs up to num/2

    for (int i = 2; i &lt;= num/2; ++i)


Actually you can do better than that you only need to run up to the sqrt(num) anything larger than this will not divide into num exactly.

    int limit = sqrt(num);
    for (int i = 2; i &lt;= limit; ++i)


Actually we can take this a step further. There is no need to divide by every number lower than num. Any number that is divisible by a prime is already checked by a prime smaller than it.

For example there is no need to check 4. You already checked 2 and all numbers divisible by 4 are also divisible by 2, so need to do that check. In fact you can skip all numbers that are not prime.

bool is_prime(int num)
{
    int limit = sqrt(num);
    for (auto const&amp; prime: primes) {
    {
        if (prime &gt; limit) {
            return true;
        }
        if (num % prime == 0) {
            return false;
        }
    }
    return true;
}