204 Count Primes

 Description:

Count the number of prime numbers less than a non-negative number, n.

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.

统计质数:给定一个非负整数n,统计出比n小的质数的个数。此题乍一看很简单,就是写一个函数判断是否为质数,再进行n次循环即可。但测试数据会出现非常大的n,用一般方法会运行超时。传统方法判断一个数是否为质数的时间复杂度为O(log2n)(与根号n作比较),n个数的时间复杂度再乘以n。

leetcode将此题标为简单,因为他给了一系列提示,给出了另外一种算法,用更多的内存换取时间上的缩短。整体思路是生成一个元素个数为n(n为输入)的数组(初始化为0),把从4开始到n结束所有的合数设置为1,再从2遍历数组,遇到为0的元素计数加一即可。我先把代码粘在下面,看不懂可以看leetcode的题目链接https://leetcode.com/problems/count-primes/ 上面有完整的hints

 1 class Solution {
 2 public:
 3     void SetFlag(vector<int>& vec, int n, int max) {
 4         long long int t = n;    //转换成长长整形,否则n平方后可能会溢出
 5         for(long long int i = t * t; i < max; i += n) {
 6             vec[i] = 1;
 7         }
 8     }
 9     int countPrimes(int n) {
10         if(n < 3) return 0;
11         // int *vec = (int *)malloc(sizeof(int) * n);
12         vector<int> vec(n + 1, 0);
13         for(int i = 2; i < n; i++) {
14             SetFlag(vec, i, n);
15         }
16         int count = 0;
17         for(int j = 2; j < n; j++) {
18             if(!vec[j]) {
19                 count++;
20             }
21         }
22         return count;
23     }
24 };
View Code
原文地址:https://www.cnblogs.com/nvbxmmd/p/4703494.html