Answer the question
In order to leave comments, you need to log in
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");
}
}
isPrime = true;
isPrime
becomes false
? 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 =) Answer the question
In order to leave comments, you need to log in
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;
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question