204. Count Primes
来源:互联网 发布:程序员平均年龄 编辑:程序博客网 时间:2024/05/22 04:58
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.
Hint:
Let's start with a isPrime function. To determine if a number is prime, we need to check if it is not divisible by any number less than n. The runtime complexity ofisPrime function would be O(n) and hence counting the total prime numbers up to n would be O(n2). Could we do better?
As we know the number must not be divisible by any number > n / 2, we can immediately cut the total iterations half by dividing only up to n / 2. Could we still do better?
超时思路:一个一个判断是否为素数。
class Solution {public:int countPrimes(int n) {switch (n){case 0:return 0;case 1:return 1;case 2:return 2;default:break;}int count = 2;for (int i = 3; i <= n; i+=2){if (isPrime(i))count++;}return count;}bool isPrime(int n){for (int i = 2; i*i < n; i++){if (n % i == 0)return false;}return true;}};
AC思路:素数筛法,埃拉托斯特尼筛选法,把质数的倍数全给标记掉,返回质数个数。
class Solution {public:int countPrimes(int n) {bool* isprime = new bool[n];for (int i = 2; i < n; i++)isprime[i] = true;int count = 0;for (int i = 2; i < n; i++){if (isprime[i]){count++;for (int j = i; j < n; j += i){isprime[j] = false;}}}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
- Mysql 命令行快速导入数据
- 黑马程序员——Java学习日志之Set集合
- 南阳题目57-6174问题
- c++算法之分解质因数
- 2946: [Poi2000]公共串 后缀数组
- 204. Count Primes
- 蛇形填数的递归实现
- iOS中单例的通用写法
- Java基础学习第二十一天——递归与字节流
- RHCE7.0-搭建基于NFS网络文件系统服务
- [POJ 2195]Going Home[费用流]
- HDU 3065 病毒侵袭持续中(AC自动机)
- HDU 4763 数据结构之KMP+二分
- CF 342div2 C 贪心