题目:
Description:
Count the number of prime numbers less than a non-negative number, n.
翻译:
描述:
计算不超过非负数n的质数的个数。
思路:
很愚蠢地用一般方法去解,即逐一判断是否为质数,对于数 i,若用i一一去除,直到计算到 i/2 都除不尽,便确定此数 i 为质数,这个一般的想法用了两层 for 循环,结果得到了Time Limit Exceeded。
无奈查看别人的答案,发现了一种算法:埃拉托斯特尼筛法。算法也很简单,下面直接给出维基百科的链接:
https://zh.wikipedia.org/wiki/%E5%9F%83%E6%8B%89%E6%89%98%E6%96%AF%E7%89%B9%E5%B0%BC%E7%AD%9B%E6%B3%95
C++代码(Visual Studio 2017):
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
/*Time Limit exceeded:
class Solution {
public:
int countPrimes(int n) {
if (n <= 0) {
return 0;
}
int count = 0;
//int c = 0;
for (int i = 2; i < n; i++) {
int c = 0;
for (int j = 2; j <= i / 2; j++) {
if (i%j == 0) {
c = 1;
break;
}
else
c = 0;
}
if (c == 0) {
count++;
//cout << i << " ";
}
}
return count;
}
};
*/
class Solution {
public:
int countPrimes(int n) {
int count = 0;
vector<bool> nums(n, true);
for (int i = 2; i < sqrt(n); i++) {
if (nums[i]) {
for (int j = i*i; j < n; j += i) {
nums[j] = false;
}
}
}
for (int i = 2; i < n; i++) {
if (nums[i] == true) {
cout << i << " ";
count++;
}
}
return count;
}
};
int main()
{
Solution s;
int n = 100;
int result;
result = s.countPrimes(n);
cout << result;
return 0;
}