Euler 007 c++ Solution

10001st prime

Problem

https://projecteuler.net/problem=7

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 10001st prime number?

Answer: 104743

Solution

euler007.cpp

#include <iostream>
#include <memory>

#include "sieve_eratos.h"

int nth_prime(size_t nth)
{
  std::unique_ptr<CSieveOfEratosthenes> sieve(new CSieveOfEratosthenes(110000));
  if( sieve ){
    return sieve->get_nth(nth);
  }
  return 0;
}

int main( int argc , char* argv[])
{
  std::cout << "Answer: " << nth_prime(10001) << std::endl;
}
```

The get_nth method:

``` cpp
int get_nth(int a_pos)
{
  int value = 0;
  int count = a_pos;
  size_t i = 0;
  for ( i = 0; i < m_primes->size() && a_pos ; i++) {
    // cout << "O: " << i << endl;
    if( true == (*m_primes)[i] ){
      // cout << "    **" << endl;
      value = i;
      a_pos--;
    }
  }

  if( a_pos == 0 ){
    return value;
  }else{
    return 0;
  }
}

See Also

# cpp go java php ruby rust javascript
1
2
3  
4    
5    
6      
7          
8          
9          
10          
11          
12          
# cpp ruby
13
14
15
16
17
18
19
20  
21  
22  
23  
24