0

I am an amateur java student, and my teacher gave me this assignment which is to write a code that list the first 100 prime numbers. Here is what I have I tried so far.

for(int i =1; true; i++) {
    int k = 0;
    for(int j = 1; j <= i; j++) {
        if(i % j == 0){
            k ++;
        }

        if(k == 2) {
            System.out.println(i);
        }
    }
}

The problem I encountered is I couldn't not stop the console to stop after a count of 100, even if I used possible mechanisms I am familiar with. for instance:

for( int i =1; true; i++) {
    int k = 0;
    for(int j = 1; j <= i; j++) {
        if(i % j == 0) {
            k ++;
        }

        int m = 0;
        if(k == 2) {
            System.out.println(i);
            m++;
            if(m==100) {
                break;
            }
        }
    }
}

Can I get help in terminating the loop after a count of 100 primes ?

jseashell
  • 745
  • 9
  • 19
  • 3
    Add another counter to count how many primes you've printed. Then, replace `true` with a check to see if the amount is less than 100 – Benjamin Urquhart May 28 '19 at 15:06
  • I don't see the logic behind your code. Why do you need two loops? This prints the same numbers multiple times. – PMF May 28 '19 at 15:08
  • Apart from the fact that you have errors in your code and it won't even compile. It really doesn't print any prime numbers currently at all. It prints every number there is starting from 2, sometimes multiple times. – OH GOD SPIDERS May 28 '19 at 15:09
  • FYI I succeeded in listing the prime numbers. The only drawback is the numbers are infinite. No numbers are repeated. – Amanuel Getachew May 28 '19 at 15:11
  • 1
    @user669545 I don't doubt that. It is just that it would have been a lot more helpful if you would have posted the code that correctly compiles and prints the prime number to your question instead of the version you used above. – OH GOD SPIDERS May 28 '19 at 15:15
  • I just saw the error. I have edited it now – Amanuel Getachew May 28 '19 at 15:17
  • I'm not posting this as an answer because the one from Vaibhav Vishal is a good complete solution, but just to let you know that the issue where your code isn't terminating is because you are declaring 'int m = 0' at the start of every iteration. m never goes above 1 – user27158 May 28 '19 at 15:46
  • Random thought: you're incrementing by 1, there's only one prime ever that's even (2). – Rogue May 28 '19 at 15:59
  • Possible duplicate of [Calculating and printing the nth prime number](https://stackoverflow.com/questions/9625663/calculating-and-printing-the-nth-prime-number) – Samuel Philipp May 28 '19 at 16:19

3 Answers3

2

You need to keep track of how many prime numbers you have printed, once it reaches 100 stop printing. I have explained the code below using comments in code.

public class Main
{
    public static void main(String[] args) {
        int k = 0;  // to keep track of how many primes you have prited
        int i = 2;  // number to check for prime, increases every loop
        while (k < 100){  // while you have printed less than 100 primes
            boolean isPrime = true;  // next few lines are checking i for prime and store it in this variable
            for(int divisor = 2; divisor <= i / 2; divisor++) {  // you should go with divisor <= Math.sqrt(i) in condition, I couldn't be bothered in import stuff.
                if (i % divisor == 0) {
                    isPrime = false;
                    break; // i is not a prime, no reason to continue checking
                }
            }
            if (isPrime){
                System.out.println(i);  // if i is prime, print it
                k ++; // increase k by when a print number is found
            }
            i ++; // increase i to check next number
        }
    }
}
Vaibhav Vishal
  • 6,576
  • 7
  • 27
  • 48
1

You code runs to infinity because you have placed your break at wrong point. Your break exits the inner loop which is for(int j = 1; j <= i; j++) although you should be targeting the outer-loop for( int i =1; true; i++) since that is what is deciding how many numbers will be printing inner-loop is just to check if the number is prime.

I have corrected your approach in this code (The explanation is in the comments)

int numbersPrinted = 0; // To keep track of how many numbers have been printed
for (int i = 2; true; i++) {
    boolean isPrime = true; // Assuming the number is prime
    for (int j = 2; j < i; j++) {
        // Checking if any number from 2 to i-1 completely divides i
        if (i % j == 0) {
            // If a number completely divides (gives 0 remainder)
            // The number is not prime
            isPrime = false;
            // You can use break here. I don't think it matters anyways.
        }
    }
    if (isPrime) {
        // Printing i only if it is prime
        System.out.print(i + ", ");
        numbersPrinted++; // Updating the numbersPrinted
    }
    // Checking if the numbers printed is grater than or equal to 100
    if (numbersPrinted >= 100)
        // This will break the outermost loop
        // This is where you messed up
        break;
}

Output (Exactly 100 prime numbers)

2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 
Samuel Philipp
  • 10,631
  • 12
  • 36
  • 56
Yoshikage Kira
  • 1,070
  • 1
  • 12
  • 20
0

To answer your question how to stop at 100:

for( int i =1; i<=100; i++){

The second argument of the for statement is the condition to continue. If this condition evaluates to false, the for loop stops iterating.

Conffusion
  • 4,335
  • 2
  • 16
  • 28