代码拉取完成,页面将自动刷新
同步操作将从 doocs/leetcode 强制同步,此操作会覆盖自 Fork 仓库以来所做的任何修改,且无法恢复!!!
确定后同步将在后台操作,完成时将刷新页面,请耐心等待。
Count the number of prime numbers less than a non-negative number, n
.
Example 1:
Input: n = 10 Output: 4 Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
Example 2:
Input: n = 0 Output: 0
Example 3:
Input: n = 1 Output: 0
Constraints:
0 <= n <= 5 * 106
class Solution:
def countPrimes(self, n: int) -> int:
if n < 2:
return 0
res = 0
primes = [True for _ in range(n)]
for i in range(2, n):
if primes[i]:
res += 1
for j in range(i * i, n, i):
primes[j] = False
return res
class Solution {
public int countPrimes(int n) {
if (n < 2) return 0;
boolean[] primes = new boolean[n];
Arrays.fill(primes, true);
int res = 0;
for (int i = 2; i < n; ++i) {
if (primes[i]) {
++res;
if ((long) i * i < n) {
for (int j = i * i; j < n; j += i) {
primes[j] = false;
}
}
}
}
return res;
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。