输入一个数,返回小于等于这个数的质数。
枚举法:
public static int countPrimes(int n) {int cnt=0;for(int i=2;i<n;i++) {if(prime(i))cnt++;}return cnt;}private static boolean prime(int x) {for(int i=2;i*i<=x;i++){if(x%i==0)return false;}return true;}
埃式筛法:
class Solution {public static int countPrimes(int n) {int cnt = 0;int arr[] = new int[n + 1];Arrays.fill(arr, 1);for (int i = 2; i < n; i++) {if (arr[i] == 1) cnt++;if ((long) i * i < n) {for (int j = 2 * i; j <= n; j += i) arr[j] = 0;}}return cnt;}
}
线性筛法:
class Solution {public static void main(String[] args) {System.out.println(countPrimes(10));}public static int countPrimes(int n) {int cnt = 0;boolean arr[] = new boolean[n + 1];for (int i = 2; i < n; i++) {if (!arr[i]) cnt++;for (int j = 2 * i; j <= n; j += i) arr[j] = true;}return cnt;}
}