//根据筛选法求出100以内的所有素数,所谓筛选法是指从小到大筛去一个以知素数的所有倍数,
//例如,根据2我们可筛去4,6,8,...98,100等数.然后根据3可筛去9,15,...99等数(注重此时6,
//12等数早就被筛去了),由于4被筛去了,下一个用于筛选的素数是5...依次类推,最后剩余的就
//是100以内的素数.
/*
*auther starshus
*
*Date 04/11/20
*/
//6.7.4
public class Prime
{
private static final int MAX=100;
public static void init(int[] num)//定义数组,里面装从1到100
{
int i=0;
for(;i<MAX;i++)
{
num[i]=i+1;
}
}
public static int count(int[] num)//在程序运行后,计算素数个数
{
int n=0,i=0;
for(;i<MAX;i++)
{
if(num[i]!=0)//非素数将被置零
n++;
}
return n;
}
public static void printf(int[] num)//输出所有素数,每10个转行一次
{
int i=0,n=0;
for(;i<MAX;i++)
if(num[i]!=0)
{
System.out.print(num[i]+" ");
n++;
if(n%10==0)
System.out.println();
}
}
public static void main(String[] args)//主方法
{
int i=2,j=1;
int count;
int[] numbers = new int[MAX];
init(numbers);
while (j<MAX)
{
if(numbers[j]!=0)
while (i<MAX)
{
if(numbers[i]!=0)
{
if(numbers[i]%numbers[j]==0)
numbers[i]=0;//假如不是素数,置零
}
i++;
}
j++;
i=j+1;
}
count=count(numbers);
printf(numbers);
System.out.println();
System.out.println("ok,we found "+count+"primes in "+MAX+" numbers.");
}
}