4 回答

TA貢獻(xiàn)1844條經(jīng)驗(yàn) 獲得超8個(gè)贊
只需在循環(huán)之前添加以下幾行for,它就會(huì)給出預(yù)期的輸出:
int x = 0;
if (first<3) {
System.out.println(2);
x++;
}
您的更新程序?qū)⑹牵?/p>
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貢獻(xiàn)1862條經(jīng)驗(yàn) 獲得超6個(gè)贊
內(nèi)循環(huán)忽略數(shù)字 2。 j < i => 2 < 2 為 false

TA貢獻(xiàn)1880條經(jīng)驗(yàn) 獲得超4個(gè)贊
您可以檢查此代碼(經(jīng)過(guò)優(yōu)化,因?yàn)樗诖蠓秶鷥?nèi)運(yùn)行得更快。在迭代所有數(shù)字之前循環(huán)返回)
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貢獻(xiàn)2012條經(jīng)驗(yàn) 獲得超12個(gè)贊
嘗試這個(gè):
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;
}
}
添加回答
舉報(bào)