标签:
public class PrimeFilter2{ public static void main(String args[]){ int a[]={2,3,5,7}; print(a); int b[] = filter(a,100); print(b); int c[] = filter(b,10000); print(c); int d[] = filter(c,100000000); print(d); } static int[] filter(int a[],int n){ //a[]={2,3,5,7} int[] b = new int[n];//0,2,3,0,5,0,7...100 b[1]=2; for(int i=2;i<n;i+=2){ b[i] = i+1; } //筛选 for(int i=1;i<a.length;i++){ int x = n/a[i]; for(int j=2;j<=x;j++){ b[ a[i]*j-1 ] = 0; } } //提取非0的数即素数 int num=1; for(int i=2;i<b.length;i+=2){ if(b[i]!=0){ num++; } } //把数组放到num个元素的数组当中 int[] c= new int[num]; c[0]=2; int k=1; for(int i=2;i<b.length;i+=2){ if(b[i]!=0){ c[k++] = b[i]; } } return c; } static void print(int[] a){ System.out.println("开始打印"+a.length+"个素数..."); for(int x: a){ System.out.print(x+" "); } System.out.println(); } }
标签:
原文地址:http://blog.csdn.net/u011479875/article/details/45309527