JAVA筛选法求N以内的质数


package cn.com.basicskill;

public class PrimeNumber {//筛选法求N以内的质数(用数组完成的不太理想,当N很大时开销大)

/**
* @param args
*/
public static void main(String[] args) {
int i,n=10;
int s=1;
int a[] = new int [n];



for(int k=0;k<n;k++){ //给数组A赋值
a[k]=k;
// System.out.println(k+"-"+a[k]+"-");
}


for(i=2;i<n;i++){ //
for(int j=i+1;j<n;j++){
if(a[j]!=0&&a[j]%i==0)
{
// System.out.println("the jjj is "+a[j]);
a[j]=0;
// System.out.println("the jjj is "+a[j]);
// System.out.println("the i is "+i);
// System.out.print("@"+j+"---"+"\n");
}
else
{
// System.out.print("the a[j] is "+a[j]);
// if(a[j]>b[s-1]){ //这里之所以错,是因为凡是不被2整除的都放进来了
// b[s]=a[j];
// System.out.print("the s is "+s+"-"+b[s]+"\n");
// s++;
// continue;
}
}
}
int t=0;
for(int k=0;k<n;k++){
if(a[k]!=0){
t++;
System.out.println("-"+k+"-"+a[k]+"-");
}
}
System.out.println("-the total number of primer number is "+t+"-");
}


}



运行结果(当N=10时)
-1-1-
-2-2-
-3-3-
-5-5-
-7-7-
-the total number of primer number is 5-
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值