简体   繁体   中英

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

I'm unsure of how to create a sequence of numbers that can be placed before each iteration of printed prime numbers. Thank you for any help you can offer.

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);
                }
        }


    }
}

Right now, my code outputs (after the user enters their two numbers):

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

What I need my code to look like:

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

Also, if you could see any errors or improvements I could change, I would greatly appreciate it. Thank you again!

You can use a counter and print the counter as you print the prime number. Increment the counter each time.

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

Just add a count variable and increment it whenever you output a number:

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

a simple change:

  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); } } } } 

Declare Count before for loop

int count = 0;

and then increment the count on every prime number.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM