找质数(枚举 埃氏筛 线性筛)

输入一个数,返回小于等于这个数的质数。

枚举法:

    public static int countPrimes(int n) {
        int cnt=0;
        for(int i=2;i

埃式筛法: 

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;
    }
}

你可能感兴趣的:(每日总结,leetcode,算法,java,算法,数据结构)