java求素数
1234567891011121314151617181920212223242526272829303132
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 + "个素数"); }}
优化后的程序
12345678910111213141516171819202122232425262728
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); }}