Home > database >  why do we use < and not <= in second loop while printing prime numbers
why do we use < and not <= in second loop while printing prime numbers

Time:07-19

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

CodePudding user response:

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.

It is not necessary to loop until the exact number you are testing, because we already know that every natural number has itself as a divisor. If you want to use to <= you have to write

for (i = 2; i <= number-1; i ) {

It is only necessary to discover if there is any natural number that is a divisor of number between 2 and number - 1. 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 3 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.

CodePudding user response:

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

  •  Tags:  
  • java
  • Related