输入:n = 10
输出:4
解释:小于 10 的质数一共有 4 个, 它们是 2, 3, 5, 7 。
package com.apesblog.day_20221212;
/**
* @author ZhangYuShun
* @since 2022/12/12
* 给定整数 n ,返回 所有小于非负整数 n 的质数的数量 。
*/
public class PrimeNumber {
public static void main(String[] args) {
int n = 499979;
int count = countPrimeByFor(n);
System.out.println(count);
count = countPrimeByEratosthenes(n);
System.out.println(count);
}
private static int countPrimeByEratosthenes(int n) {
boolean[] isPrime = new boolean[n];
for (int i = 0; i < n; i++) {
isPrime[i] = true;
}
int count = 0;
for (int i = 2; i < n; i++) {
if (isPrime[i]) {
count++;
if ((long) i * i < n) {
for (int j = i * i; j < n; j += i) {
isPrime[j] = false;
}
}
}
}
return count;
}
private static int countPrimeByFor(int n) {
int count = 0;
for (int i = 2; i < n; i++) {
if (isPrime(i)) {
count++;
}
}
return count;
}
private static boolean isPrime(int x) {
for (int i = 2; i * i <= x; i++) {
if (x % i == 0) {
return false;
}
}
return true;
}
}

评论区