class Solution { public: int countPrimes(int n) { if(n < 3) return 0; vector<int> res(n, 1); res[0] = 0; res[1] = 0; for(int i = 2; i < sqrt(n); ++i){ if(res[i] != 1) continue; for(int j = i*2; j < n; j += i){ res[j] = 0; } } int num =...
package leetcode func countPrimes(n int) int { isNotPrime := make([]bool, n) for i := 2; i*i < n; i++ { if isNotPrime[i] { continue } for j := i * i; j < n; j = j + i { isNotPrime[j] = true } } count := 0 for i := 2; i < n; i++ { if !is...
leetcode 204 Count Primes 本题使用传统方法,时间复杂度过高,会超时。从discuss学习了两种新的方法。 第一种方法: Sieve of Eratosthenes youtube视频讲解 class Solution { public int countPrimes(int n) { //Java对布尔数组初始化为false boolean[] nf = new boolean[n]; if(n < 3) return 0; int ...
2, 寻找到下一个未被筛除的数。如3. 再筛掉以3为因子的数。 3, 反复步骤2. 时间复杂度为O(n) class Solution { public: int countPrimes(int n) { vector<int> sieve(n, true); int count = 0; for (int i=2; i<n; i++) { if (sieve[i]) { ++count; for (int j=i+i; j<n;...
[LeetCode] Count Primes Problem Count the number of prime numbers less than a non-negative number, n. Note 用数组flag标记非质数,每当出现一个flag[i]为false,计数器count加一。 关于质数有三点: 大于3的质数一定是奇数,如3,5,7; 奇数中的非质数也一定是奇数的乘积。
classSolution(object):defcountPrimes(self,n):""":type n: int:rtype: int"""ifn<=2:return0prime=[True]*ni=3sqrtn=pow(n,0.5)count=n//2# 偶数一定不是质数whilei<=sqrtn:j=i*iwhilej<n:ifprime[j]:count-=1prime[j]=Falsej+=2*ii+=2whilei<=sqrtnandnotprime[i]:i+=2returncount...
class Solution { public int countPrimes(int n) { boolean[] notPrimes = new boolean[n]; int count = 0; for (int i = 2; i < n; i++) { if (!notPrimes[i]) { count++; for (int j = 2 * i; j < n; j += i) { ...
Problem List Problem List RegisterorSign in Premium Testcase Test Result Test Result All Solutions Case 1Case 2Case 3 10 9 1 2 3 › 10 0 1 Source
Run Submit Description Description Editorial Editorial Solutions Solutions Submissions Code Testcase Test Result Test Result 🔥 Join LeetCode to Code! View your Submission records here Register or Sign In Ln 1, Col 1 Case 1 Case 2 Case 3 ...
3, 反复步骤2. 时间复杂度为O(n) class Solution { public: int countPrimes(int n) { vector<int> sieve(n, true); int count = 0; for (int i=2; i<n; i++) { if (sieve[i]) { ++count; for (int j=i+i; j<n; j+=i) { ...