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 10 001st prime number?
C++:
#include <iostream> #include <cmath> using namespace std; const int MAXN = 10001; int prime[MAXN+1] = {2, 3}; bool isprime(int n) { int q=sqrt(n), i=1; while(prime[i] <= q) if(n % prime[i] == 0) return false; else i++; return true; } void maketable(int n) { int i = 2, val = 5; while(i < n) { if(isprime(val)) prime[i++] = val; val += 2; } } int main() { int n; maketable(MAXN); while(cin >> n) cout << prime[n - 1] << endl; return 0; }
C++:
#include <iostream> #include <cmath> using namespace std; const int MAXN = 10001; int prime[MAXN+2] = {2, 3, 5}; bool isprime(int n) { int q=sqrt(n), i=1; while(prime[i] <= q) if(n % prime[i] == 0) return false; else i++; return true; } void maketable(int n) { int val1 = 1, val5 = 5; for(int i=3; i<=n;) { val1 += 6; if(isprime(val1)) prime[i++] = val1; val5 += 6; if(isprime(val5)) prime[i++] = val5; } } int main() { int n; maketable(MAXN); while(cin >> n) cout << prime[n - 1] << endl; return 0; }