埃式 筛法 public int countPrimes(int n) { int res = 0; boolean[] flag = new boolean[n+1]; for(int i=2;i<n;i++){ if(!flag[i]) res++; for(int j=2*i;j<n;j+=i){ flag[j] = true; } } return res; }
// 普通优化 筛法 public int countPrimes(int n) { boolean[] nums = new boolean[n]; //只需要遍历到n的平方根 int sqrt = (int)Math.sqrt(n); for (int i = 2; i <= sqrt; i++) { if (!nums[i]) { for (int j = i * i; j < n; j += i) { nums[j] = true; } } } int res = 0; for (int i = 2; i < n; i++) { if (!nums[i]){ res++; } } return res; }