【模板小程序】求第n个质数
1 #include <iostream> 2 #include <vector> 3 using namespace std; 4 5 int nth_prime(int n) { 6 vector<int> primes(n); 7 primes[0] = 2; 8 int CntOfPrime = 1; 9 for (int i = 3; CntOfPrime < n; ++i) { 10 bool isPrime = true; 11 for (int j = 0; j < CntOfPrime && primes[j]*primes[j] <= i; ++j) { 12 if (i % primes[j] == 0) { 13 isPrime = false; 14 break; 15 } 16 } 17 if (isPrime) { 18 ++CntOfPrime; 19 primes[CntOfPrime - 1] = i; 20 } 21 } 22 return primes[n - 1]; 23 } 24 25 int main() { 26 int n; 27 while (cin >> n) { 28 cout << nth_prime(n) << endl; 29 } 30 return 0; 31 }
『注:本文来自博客园“小溪的博客”,若非声明均为原创内容,请勿用于商业用途,转载请注明出处http://www.cnblogs.com/xiaoxi666/』