java程序求素数

person smartzeng    watch_later 2017-06-03 21:02:11
visibility 4215    class java,素数,源代码    bookmark 分享

java求素数

package code;

/**
 * 
 * @author Smart
 *
 */
public class Prame {
	/**
     * @param args the command line arguments
     */
    public static void main(String[] args) 
    {
        int a,b;
        a=0;
        b=0;
        for (int i = 101; i <= 200; i++) {
        	for(int j = 2; j < i; j++) {
        		if( i%j == 0 )
        			a++;
    		}
            if ( a < 1 ) {
            	b++;
            	System.out.println(i);
            	a = 0;
            } else
                a = 0;
        }
        // TODO code application logic here
        System.out.println("101至200之间有" + b + "个素数");
    }
}

优化后的程序

package code;

/**
 * 
 * @author Smart
 *
 */
public class PrameB {
	/**
     * @param args the command line arguments
     */
	public static void main(String[] args) {
		int count = 0;
        for	(int i = 101; i < 200; i += 2) {
            boolean b = false;
            for(int j=2; j <= Math.sqrt(i); j++) {
            	if(i % j == 0) { 
            		b = false; break; 
        		} else
    				b = true;                                       
            }
            if(b == true) {
        		count ++;System.out.println(i );
        	}
        }
        System.out.println( "素数个数是: " + count);
	}
}


评论区
评论列表
menu