Table of contents title
Question description
Given the interval [L, R], please count the number of prime numbers in the interval.
Input
Input description:
Two numbers L and R.
Input example:
2 11
output
Output description:
One line, the number of prime numbers in the interval.
Output sample:
5
HINT: Time limit: 1.0s Memory limit: 256.0MB
2 <= L <= R <= 2147483647 R-L <= 1000000
Problem-solving ideas
Just judge the number of prime numbers in the interval directly, and be careful to remove even numbers.
code
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
int m=scanner.nextInt(); //输入左区间
int n=scanner.nextInt(); //输入右区间
int b = 0; //判断是否为素数的条件
int a = 0; //记录素数的个数
for (int i=m;i<=n;i++){
//循环区间内的数
if(i!=2&&i%2==0){
//判断是否为偶数且不为2 &&:和, ||:或
continue; //跳过本次循环
}
for (int j=3;j<i;j+=2){
//循环判断是否为素数
if (i%j==0){
b++;
break; //如果不是素数结束循环
}
}
if (b==0){
//素数个数加1
a++;
}
b=0; //重置判断条件
}
System.out.println(a); //输出素数个数
}
}