/**
* 通过暴力算法和埃筛算法实现素数的统计
* @author :彭先生
*/
public class StatisticalPrime {
/**
* 暴力算法
* @return
*/
public static int force(int n){
int count = 0;
for (int i = 2; i < n; i++) {
boolean flag = false;
for (int j = 2; j < i; j++) {
if(i % j == 0){
flag = true;
break;
}
}
if(!flag){
count++;
}
}
return count;
}
/**
* 埃氏筛选法
* @return
*/
public static int SievingMethod(int n){
//boolean默认值为false,变量取名为【not】,先默认将所有的数据都标识为【是素数】
boolean[] isNotPrime = new boolean[n];
int count = 0;
for (int i = 2; i < n; i++) {
if(!isNotPrime[i]){
count++;
for (int j = i * i; j < n; j+=i) {
isNotPrime[j] = true;
}
}
}
return count;
}
public static void main(String[] args) {
System.out.println("暴力算法:" + force(100));
System.out.println("埃氏筛选法:" + SievingMethod(100));
}
}
分别通过暴力算法和埃氏筛选法统计素数数量
最新推荐文章于 2024-04-24 15:47:54 发布