簡體   English   中英

如何在此素數生成器中實現數字序列?

[英]How can I implement a sequence of numbers in this Prime number generator?

我不確定如何創建可以在每次打印質數迭代之前放置的數字序列。 感謝您提供的任何幫助。

public class CountingPrimes {

public static void main(String[] args) {
    int flag = 0, i, j;
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter the 1st number: ");
    int firstNum = sc.nextInt();

    System.out.println("Enter the 2nd number: ");
    int secondNum = sc.nextInt();
    System.out.println("Counting prime numbers between "
            + firstNum + " and " + secondNum + ":");
    for (i = firstNum; i <= secondNum; i++) {
        for (j = 2; j < i; j++) {
            if (i % j == 0) {
                flag = 0;
                break;
            } else {
                flag = 1;
            }
        }
        if (flag == 1) {      
            System.out.println(i);
                }
        }


    }
}

現在,我的代碼輸出(在用戶輸入兩個數字之后):

Counting prime numbers between 1 and 14:
 3
 5
 7
 11
 13

我需要我的代碼看起來像什么:

Counting prime numbers between 1 and 14:
1. 3
2. 5
3. 7
4. 11
5. 13

另外,如果您看到我可以更改的任何錯誤或改進,我將不勝感激。 再次感謝你!

您可以使用計數器並在打印質數時打印計數器。 每次增加計數器。

int counter = 1;
int flag = 0, i, j;
.....
if (flag == 1) {
    System.out.format("%d. %d\n", counter, i);
    counter++;
}

只需添加一個count變量,並在輸出數字時將其遞增:

...
int count = 0;
for (i = firstNum; i <= secondNum; i++) {
    ...
    if (flag == 1) {
        count++;
        System.out.format("%d. %d%n", count, i);
    }
}

一個簡單的變化:

  import java.util.Scanner; public class CountingPrimes { public static void main(String[] args) { int flag = 0, i, j; int count = 0; Scanner sc = new Scanner(System.in); System.out.println("Enter the 1st number: "); int firstNum = sc.nextInt(); System.out.println("Enter the 2nd number: "); int secondNum = sc.nextInt(); System.out.println("Counting prime numbers between " + firstNum + " and " + secondNum + ":"); for (i = firstNum; i <= secondNum; i++) { for (j = 2; j < i; j++) { if (i % j == 0) { flag = 0; break; } else { flag = 1; } } if (flag == 1) { System.out.println(++count + "." + i); } } } } 

在for循環之前聲明計數

int count = 0;

然后增加每個素數的計數。

 if (flag == 1) {      
        System.out.println(++count+". "+i);
            }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM