/*
* 判断101-200之间有多少个素数,并输出所有素数。
public static void main(String[] args) {
test();
}
public static void test(){
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);
}
}
* 判断101-200之间有多少个素数,并输出所有素数。
*/
任意一整数整除。因此判断一个整数m是否为素数,只需用2~m-1之间的每一个整数去除,如果都不能被整除,那么m就是一个素数。
其实可以简化,m不必被2~m-1之间的每一个整数去除,只需被2~根号m之间的每个数去除就可以了。例如判别17是否为素数,只需使2~4之间的每一个整数去除。为什么可以做如此简化呢?因为如果m能被2~m-1之间任意整数整除,如果这个数大于根号m,那这个数必定对应的还有一个比根号m小的因子(以16为例,2、8是它的因子,8大于4,2小于4)。
public static void main(String[] args) {
test();
}
public static void test(){
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);
}
}