[ref]
https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
https://leetcode.com/discuss/34622/my-c-solutions-in-44ms-time-nearly-o-n-and-space-nearly-o-n
public class Solution {
// https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
// https://leetcode.com/discuss/34622/my-c-solutions-in-44ms-time-nearly-o-n-and-space-nearly-o-n
public int countPrimes(int n) {
if (n < 3) return 0;
int sqrtN = (int)Math.sqrt(n); // trick 0: use sqrt
int counter = n / 2; //trick 1: all even num except 2 is not prime
boolean[] prime = new boolean[n];
for (int i = 1; i < n; i += 2)
prime[i] = true;
for (int i = 3; i <= sqrtN; i += 2) { // trick 2: skip even num
if (prime[i]) {
// mark multiples of i not prime
for (int j = i * i; j < n; j += i) { // trick 3: start from i*i
if (prime[j]) {
prime[j] = false;
counter--; // trick 4: avoid another loop
}
}
}
}
return counter;
}
}
分享到:
相关推荐
java入门 java_leetcode题解之204_Count_Primes
python python_leetcode题解之204_Count_Primes.py
c++ C++_leetcode题解之204_Count_Primes.cpp
java java_leetcode题解之Count Primes.java
Count Primes**:虽然不是直接的LRU问题,但可以使用LRU缓存优化解决方案,避免重复计算素数。 通过分析并解决这些LeetCode题目,开发者可以深入理解LRU缓存的工作原理,并提高其编程技巧。这个项目"leetcode-java...
# [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License]...
def countPrimes(n): if n return 0 primes = [True] * n primes[0], primes[1] = [False, False] for i in range(2, int(n**0.5)+1): if primes[i]: for j in range(i*i, n, i): primes[j] = False ...
countPrimes(int n) { if (n isPrime(n+1, 1); int count = 1; for (int i=3; i<n; i+=2){ if (isPrime[i]==1) { count++; for (int j = i; j<=n/i; j+=2) isPrime[j*i] = 0; } } return count; } :star: 2020...
public int countPrimes(int n) { if (n ) return 0; boolean[] isPrime = new boolean[n]; Arrays.fill(isPrime, true); int count = 0; for (int i = 2; i * i ; i++) { if (isPrime[i]) { count++; for...
LeetCode 204的题目是“计数质数”(Count Primes),要求统计所有小于非负整数n的质数的数量。解决这个问题的关键是高效地识别质数,并减少不必要的重复检查。在C#中,一个常见的解决方案是使用埃拉托斯特尼筛法...
countPrimes(int n) { int count = 0; for(int i = 2; i < n; i++) { bool sign = true; for(int j = 2; j < i; j++) { if(i % j == 0) { sign = false; break; } } if(sign) count++; ; } return count; } ...
1.7 Count Primes(质数的个数) 2. Algorithm Implementation Questions (算法实现题) 3. Linked List Questions(链表相关问题) 4. Array Questions(数组相关问题) 5. Binary Tree Questions(二叉树相关问题...
29. **Count Primes**:计数素数。可以使用埃拉托斯特尼筛法(Sieve of Eratosthenes)来高效找出一定范围内的素数。 以上就是LeetCode中部分Python编程题目的解析概述,通过这些题目,可以深入理解Python编程、...
leetcode数组下标大于间距 problems 1.Exercise ...CountPrimes:计算小于n的素数个数,数学 bestsubstring:将字符串尽可能分割为多个部分,各子串不包含相同字符暴力 2pow:计算2的N次幂 dp/ chrous:相