题目链接:count-primes
Description:
Count the number of prime numbers less than a non-negative number, n
public class Solution { public int countPrimes(int n) { if(n <= 2) return 0; List<Integer> primes = new ArrayList<Integer>(); primes.add(2); for (int i = 3; i < n; i += 2) { int sqrt_i = (int) Math.sqrt(i); for (int j = 0; i % primes.get(j) != 0; j++) { if (primes.get(j) > sqrt_i) { primes.add(i); break; } } } return primes.size(); } }
时间: 2024-11-03 22:47:30