204. Count Primes
来源:互联网 发布:logo在线制作软件 编辑:程序博客网 时间:2024/05/26 20:20
题目:
Description:
Count the number of prime numbers less than a non-negative number, n.
题意:统计小于非负整数n的素数的个数,素数不能被比它小的整数整除。
思路:
解题思路入提示二所示,埃拉托斯特尼筛法Sieve of Eratosthenes中,算法过程如下图所示,我们从2开始遍历到根号n,先找到第一个质数2,然后将其所有的倍数全部标记出来,然后到下一个质数3,标记其所有倍数,一次类推,直到根号n,此时数组中未被标记的数字就是质数。我们需要一个n-1长度的bool型数组来记录每个数字是否被标记,长度为n-1的原因是题目说是小于n的质数个数,并不包括n。 然后我们用两个for循环来实现埃拉托斯特尼筛法。
代码:312ms
class Solution {public: int countPrimes(int n) { vector<bool> result(n-1, true); result[0] =false; int count = 0, last = sqrt(n); for(int i=2; i<=last; i++){ if(result[i-1]){ for(int j=i*i; j<n; j+=i){ result[j-1] = false; } } } for(int i=0; i<n-1; i++){ if(result[i]){ ++count; } } return count; }};代码:216ms
class Solution {public: int countPrimes(int n) { if(n<=2){ return 0; } vector<bool> result(n, false); int count = 1, last = sqrt(n); for(int i=3; i<n; i+=2){ if(!result[i]){ count++; if(i>last){ continue; } for(int j=i*i; j<n; j+=i){ result[j] = true; } } } return count; }};代码:16ms
class Solution {public: int countPrimes(int n) { if(n<=2){ return 0; } int count = n>>1, last = sqrt(n-1); bool *table = new bool[n]; for(int i=3,j,step; i<=last; i+=2){ if(!table[i]){ for(step=i<<1, j=i*i; j<n; j+=step){ if(!table[j]){ table[j] = 1; count--; } } } } delete[] table; return count; }};代码:12ms
class Solution {public: int countPrimes(int n) { if(--n < 2) return 0; int m = (n + 1)/2, count = m, k, u = (sqrt(n) - 1)/2; bool notPrime[m] = {0}; for(int i = 1; i <= u;i++) if(!notPrime[i]) for(k = (i+ 1)*2*i; k < m;k += i*2 + 1) if (!notPrime[k]) { notPrime[k] = true; count--; } return count; }};
0 0
- 204. Count Primes
- 【LeetCode】204.Count Primes
- [leetcode] 204.Count Primes
- LeetCode 204. Count Primes
- Leetcode 204. Count Primes
- 204. Count Primes
- 204. Count Primes
- [LeetCode]204. Count Primes
- 204. Count Primes LeetCode
- 204. Count Primes
- 204. Count Primes
- 204. Count Primes
- 204. Count Primes
- LeetCode *** 204. Count Primes
- 204. Count Primes
- LeetCode 204. Count Primes
- leetcode-204. Count Primes
- 204. Count Primes
- warning: format ‘%s’ expects argument of type ‘char *’和warning: backslash and newline separated by
- 学习SpringMVC(二十四)之异常处理
- 如何让服务器支持跨域
- service
- linux下安装jdk及配置环境变量
- 204. Count Primes
- iOS的主要框架介绍
- NGUI中sprite出现透明边框(黑线)
- HDR全局色调映射算法实现
- VC++ 之获取主机IP gethostbyname()函数 详细实例分析
- codeforces 651A A. Joysticks
- java中的线程优先级的作用
- C++编程基础笔记章节九
- Macros with a Variable Number of Arguments.