1到100的素数(java)

 

public class test02 {

	/**
	 * @param args
	 * yhliang
	 * 求1到100的素数
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int a[]=new int[100];
		int c[] =new int[50];
        boolean b;
        int n=0;
        /*
         * 把1到100存入到一个整型数组中
         */
        for(int i=0;i<100;i++){
        	a[i]=i+1;	
        }
        for(int i=0;i<a.length;i++){
           System.out.print(a[i]+"--");
        	if(i==49){
        		System.out.println();
        	}        	
        }
       
       System.out.println();
       
       /*
        * 关键代码
        */
       for(int i=0;i<100;i++){
    	   if(a[i]>1){
    		   b=true;
       	    for(int j=1;j<i;j++){
       	    	if(a[i]%a[j]==0){
       	    		b=false;
       	    		break;
       	    	}
       	    }
       	    if(b){
       	    	System.out.print(a[i]+" ");    
       	    	c[n]=a[i];
       	    	n++;
       	    }
    	   }else{
    		   System.out.println(a[i]+"不是素数!");
    	   }
    	 
       }
       display(c,n);
	}

	private static void display(int[] c,int count) {
		// TODO Auto-generated method stub
		System.out.println();
		System.out.println("1到100之间的素数如下:");
		StringBuffer sb=new StringBuffer();
		for(int i=0;i<count;i++){
		  sb.append(c[i]);
		  if(i<count-1){
			  sb.append(",");
		  }
		}
		
		System.out.println(count);
		System.out.print(sb.toString());
	}

}

 

posted @ 2011-11-10 14:03  月亮的影子  阅读(1818)  评论(0编辑  收藏  举报