当前位置:首页 > 编程笔记 > 正文
已解决

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

来自网友在路上 163863提问 提问时间:2023-11-02 01:17:57阅读次数: 63

最佳答案 问答题库638位专家为你答疑解惑

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

枚举法:

    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;}
}
查看全文

99%的人还看了

猜你感兴趣

版权申明

本文"找质数(枚举 埃氏筛 线性筛)":http://eshow365.cn/6-29757-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!