Description:
Given the prime number
n
, output the number of prime numbers
Example:
Given n = 3
, return 2
.
explanation:
[2,3,5], 3 is the second prime number.
Given n = 11
, return 5
.
explanation:
[2,3,5,7,11], 11 is the fifth prime number.
Solution:
利用一个bool数组进行标记采用平凡除法(厄尔托塞筛选法)不断剔除非质数的项,有个问题,算法啊虽然出来了,但是为什么从第一层循环从i = 2开始,可以保证剔除所有的合数(合数有哪些共有的质因子,保证算法的准确性),目前还弄不明白。
class Solution { public: /** * @param n: the number * @return: the rank of the number */ int kthPrime(int n) { // write your code here if (1 == n) return 0; int count = n; bool *flag = new bool[n+1]; for (int i = 0; i < n + 1; ++i) flag[i] = true; for (int i = 2; i <= sqrt(n); ++i) { for (int j = i * i; j <= n; j += i) { if (true == flag[j]) { flag[j] = false; --count; } } } delete flag; flag = nullptr; return count - 1; } };
附:看到一篇非常好的,讲解判断单个质数的博客,分享一下,如有侵权,请联系删除