LeetCode 204. Count Primes
原题链接在这里:https://leetcode.com/problems/count-primes/
题目:
Given an integer n
, return the number of prime numbers that are strictly less than 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
题解:
网上查查,原来有一种方法叫:Sieve of Eratosthenes 的方法.
Time Complexity: O(sqrt(n) * loglogn).
Space: O(n).
AC Java:
1 public class Solution { 2 public int countPrimes(int n) { 3 if(n < 3){ 4 return 0; 5 } 6 boolean [] isPrime = new boolean[n]; 7 Arrays.fill(isPrime, true); 8 int res = n-2; 9 for(int i = 2; i*i<n; i++){ 10 if(isPrime[i]){ 11 for(int j = i; i*j<n; j++){ 12 if(isPrime[i*j]){ 13 isPrime[i*j] = false; 14 res--; 15 } 16 } 17 } 18 } 19 return res; 20 } 21 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】博客园2025新款「AI繁忙」系列T恤上架,前往周边小店选购
【推荐】凌霞软件回馈社区,携手博客园推出1Panel与Halo联合会员
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步