判斷素數的方法:用一個數分別去除2到sqrt(這個數),如果能被整除, 則表明此數不是素數,反之是素數。
package primeNumber;
public class TestDemo {
public static void main(String[] args) {
int count = 0;
//每次+2是爲了去掉偶數,因爲102是偶數
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);
}
}