D
D
Denis Karakchiev2015-08-18 21:49:58
Java
Denis Karakchiev, 2015-08-18 21:49:58

Problem with understanding the algorithm for finding prime numbers?

The task from Schildt- a beginner's guide is to write a program that finds prime numbers from 2 to 100.
Answer:

int i, j;
 boolean isPrime;

    for(i=2; i<100; i++) {
      isPrime = true;

      for (j=2; j<(i/j); j++) {
        if((i%j) == 0) isPrime = false;
      }

      if(isPrime) {
        System.out.println(i + " is prime");
      }
}

The code is working, but a few things are completely incomprehensible to me:
1. Why do we first declare
isPrime = true;
but the output is, if the remainder of the division is 0, then the number is prime, while it isPrimebecomes false?
2. Why in the second cycle j<(i/j), why not just create j<100, because in fact you need to divide the numbers by 1 and themselves without a remainder? It is divisible by 1 because it is a variable int, by itself without a remainder, because i%j. I don’t understand this moment at all, and after all, if you ask j<100, it flatly refuses to work =)
Thanks in advance to those who answered and explained.
P.s. Before that, I was not engaged in programming, the tower is completely out of my profile.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Movchan, 2015-08-18
@Satori_Kanzo

1. Something like a proof of the opposite: first, we assume that the number is prime isPrime = true;And if there is a number, the division by which occurs completely, that is, the remainder of the division is zero if((i%j) == 0), then the opposite is proved, this number is composite: isPrime = false;
2. In order not to do extra iterations, if there is a number N, then it is enough to check only its divisors from 2 to √N.
PS If you put i < 100, then the number itself will go into the check, and since the number is completely divisible by itself, the remainder will be 0 and the condition will not work correctly. The inner loop iterates over the divisors of the number, and for the number N, they are in the range [1, N], however, since prime numbers are divisible by 1 and themselves, only the range (1, N) needs to be checked.
All divisors greater than √N result in integers less than √N as a result of division, and since we have already sorted out smaller numbers, there is no point in checking larger ones. The condition j<(i/j)just ensures the enumeration of integers in the range [2, √N].
You can also add a little optimization:

for (j=2; j<(i/j); j++) {
        if((i%j) == 0) {
                isPrime = false;
                break;
        }
      }

If you find one divisor, that's enough. It is not necessary to sort out the rest.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question