| 统计给定的两个数之间的素数的个数 | |
| 描述: |
素数是指在一个大于1的自然数中,除了1和此整数自身外,不能被其他自然数整除的数。 给定两个数字m和n,统计这两个数字之间素数的个数。 |
| 运行时间限制: | 无限制 |
| 内存限制: | 无限制 |
| 输入: |
输入为两个整数:m和n |
| 输出: |
输出m和n之间的素数的个数 |
| 样例输入: |
0 10 |
| 样例输出: |
4 |
import java.util.*;
public class Main5{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
while(in.hasNext()){
String[] strA = in.nextLine().split(" ");
int a = Integer.parseInt(strA[0]);
int b = Integer.parseInt(strA[1]);
if(a>b){ // 需要增加
int t = a;
a = b;
b = t;
}
long count = countPrime(a,b);
System.out.println(count);
}
in.close();
}
public static long countPrime(int a,int b){
long count = 0;
for(int n=a;n<=b;n++){
if(isPrime(n)){
count++;
}
}
return count;
}
public static boolean isPrime(int n){
if(n<=1){
return false;
}
if(n==2||n==3){
return true;
}
if(n%2==0 ||n%3==0){
return false;
}
for(int i=5;i<Math.sqrt(n)+1;i++){
if(n%i==0){
return false;
}
}
return true;
}
}
来源:https://www.cnblogs.com/theskulls/p/5707274.html