In the textbook Schildt met the program, wrote a simple number or not, but I can not understand how isPrime works here.

int num; boolean isPrime; num = 9; if(num < 2) isPrime = false; else isPrime = true; for(int i=2; i <= num/i;i++) { if((num % i) == 0) { isPrime = false; break; } } if (isPrime) System.out.println("Простое"); else System.out.println("He простое"); 

Help to understand, please.

  • What exactly can you not understand? - a_gura

1 answer 1

Read first what the Sieve of Eratosthenes is - in fact, the code implements the sieve of Eratosthenes.

  • in fact, there is implemented a simple check of dividing a number into all the numbers previous to it in order, if there is one - the number is not simple, this solution is a check by definition, I don’t see here a sieve. - Gorets
  • @Gorets you are inconsiderate: pay attention to a piece of for(int i=2; i <= num/i;i++) — not all numbers pass through there :) - Barmaley
  • This code is greatly accelerated if, instead of i ++, you write i + = 2 and start the cycle with 3. Yes, you need to check for divisibility by two separately. - KoVadim