0

Below is the code snipent first loop contains numbers from 1 to 100 and second loop to iterate through numbers , in second loop if we use <= prime numbers are not getting printed

public class primeNumbers {

 public static void main(String args[]) {
    int i, number, count;

    System.out.println("Prime Numbers from 1 to 100 are : ");
    for (number = 1; number <= 100; number++) {
        count = 0;
        for (i = 2; i <= number; i++) {
            if (number % i == 0) {
                count++;
                break;
            }
        }
        if (count == 0 && number != 1) {
            System.out.print(number + " ");
        }
    }
 }
}
GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • 4
    `number` is __always__ divisible by `number`. Thats why we stop one before. – tkausl Jul 19 '22 at 06:44
  • 1
    Note: learn about java naming conventions. Class names go CamelCase, so always start uppercase. Also note that java isn't C, you really should declare your variables before using them. – GhostCat Jul 19 '22 at 09:08

2 Answers2

1

We know that

Every natural number has both 1 and itself as a divisor. If it has any other divisor, it cannot be prime.

from https://en.wikipedia.org/wiki/Prime_number.

In addition to this, it is only necessary to loop from 2 until the square root of the number you are testing (explained here).

This way we can write the second loop as:

for (i = 2; i <= Math.sqrt(number); i++) {

It is only necessary to discover if there is any natural number that is a divisor of number between 2 and Math.sqrt(number) - inclusively. If this is the case, number is not a prime. Otherwise it is a prime.

E.g.: Let's see the case where number = 4. We already know that the number 4 has 1 and itself (4) as divisors. So, we want to loop from 2 to Math.sqrt(4) = 2 to discover if there are any more divisors. And in this case in the first iteration where i = 2, we find that (4 % 2) == 0. So 4 is not prime.

This would be written like this:

public static void main(String[] args) {
    System.out.println("Prime Numbers from 1 to 100 are:");
    for (int number = 2; number <= 100; number++) {
        boolean isPrime = true;
        for (int i = 2; i <= Math.sqrt(number); i++) {
            if (number % i == 0) {
                isPrime = false;
                break;
            }
        }
        if (isPrime) {
            System.out.print(number + " ");
        }
    }
}
hugoalexandremf
  • 166
  • 1
  • 1
  • 9
0

prime numbers are divisible by 1 and itself. The second loop run from 2, which means that when you check one number is divisible by itself, that does not make sense. using " < " is optimise

Hoang Phan
  • 23
  • 7