java从键盘输入两个正整数M,N组成。 输出一个整数,表示介于M,N之间(包括M,N)的素数的数量。(素数就是

2025-02-24 18:17:15
推荐回答(3个)
回答1:

import java.util.Scanner;
public class Test
{
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
int count = 0;
int num = scan.nextInt();
for(int i = 1;i<=num;i++){
count +=i;
}
System.out.println(count);
}
}

回答2:

import java.util.Scanner;

public class PrimeCheck {
public static void main(String args[]){
System.out.println("Please input two positive integers:");
Scanner sc = new Scanner(System.in);
try{
int a = sc.nextInt();
int b= sc.nextInt();
if(a>b){
int temp = a;
a=b;
b=temp;
}
int n = check(a,b);
System.out.printf("There are %d prime between %d and %d\n",n,a,b);
}catch(Exception e){
System.out.println("Illegal input !!!\nPlease check the number " +
"to insure they are positive integers");
}

}
private static int check(int a,int b){
int n = 0;
if(a==1) a++;
for(int i=a;i<=b;i++){
boolean flag = true;
for(int j=2;j<=Math.sqrt(i);j++){
if(i%j==0){
flag = false;
break;
}
}
if(flag) n++;
}
return n;
}
}

回答3:

import java.util.Scanner;

public class PrimeCheck {
public static void main(String args[]){
System.out.println("Please input two positive integers:");
Scanner sc = new Scanner(System.in);
try{
int a = sc.nextInt();
int b= sc.nextInt();
if(a>b){
int temp = a;
a=b;
b=temp;
}
int n = check(a,b);
System.out.printf("There are %d prime between %d and %d\n",n,a,b);
}catch(Exception e){
System.out.println("Illegal input !!!\nPlease check the number " +
"to insure they are positive integers");
}

}
private static int check(int a,int b){
int n = 0;
if(a==1) a++;
for(int i=a;i<=b;i++){
boolean flag = true;
for(int j=2;j<=Math.sqrt(i);j++){
if(i%j==0){
flag = false;
break;
}
}
if(flag) n++;
}
return n;
}
}
经测试,完全正确。