4 回答
TA贡献1844条经验 获得超8个赞
只需在循环之前添加以下几行for,它就会给出预期的输出:
int x = 0;
if (first<3) {
System.out.println(2);
x++;
}
您的更新程序将是:
import java.util.Scanner;
class Main {
public static void main(String args[]) {
int first, last, flag = 0, i, j;
Scanner scanner = new Scanner(System.in);
System.out.print("\nEnter the lower bound : ");
first = scanner.nextInt();
System.out.print("\nEnter the upper bound : ");
last = scanner.nextInt();
System.out.println("The prime numbers in between the entered limits are :");
int x = 0;
if (first<3) {
System.out.println(2);
x++;
}
for (i = first; i <= last; i++) {
for (j = 2; j < i; j++) {
if (i % j == 0) {
flag = 0;
break;
} else {
flag = 1;
}
}
if (flag == 1) {
x++;
System.out.println(i + " ");
}
}
System.out.println("Total number of prime numbers between " + first + " and " + last + " are " + x);
}
}
TA贡献1880条经验 获得超4个赞
您可以检查此代码(经过优化,因为它在大范围内运行得更快。在迭代所有数字之前循环返回)
public static void main(String args[]) {
int first;
int last;
Scanner scanner = new Scanner(System.in);
System.out.print("\nEnter the lower bound : ");
first = scanner.nextInt();
System.out.print("\nEnter the upper bound : ");
last = scanner.nextInt();
System.out.println("The prime numbers in between the entered limits are :");
int x = 0;
for (int i = first; i <= last; i++) {
if (isPrime(i)) {
x++;
System.out.println(i + " ");
}
}
System.out.println("Total number of prime numbers between " + first + " and " + last + " are " + x);
}
static boolean isPrime(int n)
{
if (n <= 1) //less than 2 are not
return false;
if (n <=3) // 2 and 3 are prime
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
for (int i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
你不需要旗帜。
TA贡献2012条经验 获得超12个赞
尝试这个:
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
int i, n;
int num;
int maxCheck;
boolean isPrime = true;
String primeNumbersFound = "";
Scanner sc=new Scanner(System.in);
System.out.println("Enter the first number: ");
num = sc.nextInt();
System.out.println("Enter the second number: ");
maxCheck= sc.nextInt();
for (i = num; i <= maxCheck; i++) {
isPrime = CheckPrime(i);
if (isPrime) {
primeNumbersFound = primeNumbersFound + i + " ";
}
}
System.out.println("Prime numbers from " + num + " to " + maxCheck + " are:");
System.out.println(primeNumbersFound);
}
public static boolean CheckPrime(int n) {
int remainder;
for (int i = 2; i <= n / 2; i++) {
remainder = n % i;
if (remainder == 0) {
return false;
}
}
return true;
}
}
添加回答
举报