LeetCode: Count Primes(计算n以内素数个数:高效算法)
2016-07-22 11:07
429 查看
LeetCode: Count Primes(计算n以内素数个数:高效算法)
Description:Count the number of prime numbers less than a non-negative number, n.
A prime number is a natural number that has exactly two distinct natural number divisors: 1 and itself.
https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Algorithm_complexity
埃拉托色尼筛选法:Sieve of Eratosthenes。
时间复杂度:O(n log log n)。
下面是图示过程,还有leetcode上hint用java编写的。
class Solution { public: int countPrimes(int n) { if(!n||n==1) return 0; vector<bool> isPrime(n,true); // Loop's ending condition is i * i < n instead of i < sqrt(n) // to avoid repeatedly calling an expensive function sqrt(). for(int i=2;i*i<n;++i) { if(!isPrime[i]) continue; //填表起点i*i,如3*3,因为3*2已填,步长+i for(int j=i*i;j<n;j+=i) { isPrime[j]=false; } } int count=0; for(int i=2;i<n;++i) { if(isPrime[i]) ++count; } return count; } };
别人代码用的i*i与n比较,值得学习: Loop’s ending condition is i * i < n instead of i < sqrt(n) to avoid repeatedly calling an expensive function sqrt().
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解