思路:用循环先把2的倍数做标志,然后把3的倍数做标志,以此递推。最后boolean数组中标志为false的即为素数。
import java.util.Scanner;
/**
*
* @author lenovo
*/
public class JavaApplication12 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner input = new Scanner(System.in);
int count = 0;
int n = input.nextInt();
boolean[] boo = new boolean[n+1];//因为要检索到n所以数组下标得加1
int[] array = new int[n+1];
//把各个素数的倍数标志
long time1 = System.currentTimeMillis();
for(int i = 2; i <= n; i++)
{
if(boo[i] != true)
{
array[count++] = i;
}
for(int j = i+i; j <= n; j += i )
{
boo[j] = true;
}
}
for(int i:array)
{
if(i != 0)
System.out.print(i+" ");
}
System.out.println();
//这种筛法比较适合数据较小的
long time2 = System.currentTimeMillis();
System.out.println(time2 - time1+"ms");
}
}