-3

I typed this piece of code for finding all the prime numbers between 0 and 100, but it gives output with multiples of other numbers. How can I rectify this?

public class PrimeNumbers {

    public static void main(String[] args) {
        int count = 0;
        int n = 0;
        for (n = 2; count <= 100; n++) {

            for (int j = 2; j < n; j++) {

                while (n % j == 0) {

                    j = 2;

                    n++;
                }
            }
            count++;
            System.out.println(n);
        }
    }
}
Jim Lewis
  • 43,505
  • 7
  • 82
  • 96
  • You are using `n` both for the loop and the primes counter. You need separate variables. – Michael Jul 19 '19 at 22:58
  • Possible duplicate of [How to find prime numbers between 0 - 100?](https://stackoverflow.com/questions/11966520/how-to-find-prime-numbers-between-0-100) – Michael Jul 19 '19 at 23:02

1 Answers1

0

Make sure to read the other answers and understand the issue in your code. The error can be fixed with some minor changes:

public class PrimeNumbers{
    public static void main(String[] args) {
        for (int n = 2; n <= 100; n++) {
            boolean isPrime = true;
            for (int j = 2; j < n; j++) {
                if (n % j == 0) {
                    isPrime = false;
                    break;
                }
            }
            if (isPrime) {
                System.out.println(n);
            }
        }
    }
}
käyrätorvi
  • 371
  • 1
  • 9