一、暴力求解
优化(判断是否为偶数,j * j <= x)
package leetcode;
class Solution {
public static void main(String[] args) {
System.out.println(primezNum(100));
}
// 暴力求解
public static int primezNum(int n) {
int count = 0;
for (int i = 2; i < n; i++) {
count += isPrime(i) ? 1 : 0;
}
return count;
}
private static boolean isPrime(int x) {
// j * j <= x
for (int j = 2; j < x; j++) {
if (x % j == 0) {
return false;
}
}
System.out.println(x);
return true;
}
}
二、埃筛选
public static int eratosthenes(int n) {
// 为素数和合数建立标志为
boolean[] isPrime = new boolean[n]; // 默认false为质数
int count = 0; // 统计素数个数
for (int i = 2; i < n; i++) {
if (!isPrime[i]) {
count++;
// 2 * i 计算会有重复
for (int j = i * i; j < n; j += i) { // 2 * 2 3 * 2
isPrime[j] = true;
}
}
}
return count;
}