I have a program which checks whether a given number from 0 to 9999 is a prime number or not (It was provided as a sample solution):
public class Primzahl {
public static void main(String[] args) {
for (int i = 0; i < 10000; i ) {
System.out.println(i " " isPrimzahl(i));
}
System.out.println();
}
public static boolean isPrimzahl(int zahl) {
for (int i = 2; i < (zahl / 2 1); i ) {
if (zahl % i == 0) {
return false;
}
}
return true;
}
}
However, I am having problems with understanding parts of the code:
i < (zahl / 2 1)
How is this part working?
And:
if (zahl % i == 0) {
return false;
}
With how many numbers is a given zahl
checked in this program?
Edit: typo.
CodePudding user response:
i < (zahl / 2 1)
This is just setting the upper bound of the loop to half of the input number. Operator precedence means it will divide zahl by 2 before adding 1. There is no chance that the number will divide by something more than half of its value, so the loop can terminate there if no divisor has been found.
if (zahl % i == 0) {
return false;
}
This causes it to exit the loop if an exact divisor has been found. % is the modulus operator so zahl % i == 0
means that zahl divides exactly by i and so the number cannot be prime.
The program checks whether any numbers from 2 to zahl/2 (in increments of 1) divides exactly into the input number.
CodePudding user response:
i < (zahl / 2 1)
divide zahl
by two, then add one. Since integer division is used, any fractions are ignored. That means for 13 you would get 6, add one and the result is 7.
Since you compare whether i
is smaller, the whole expression will be true for 2, 3, 4, 5, 6.
zahl % i == 0
That one performs the same integer division but just returns the remainder. If the remainder is zero, the zahl cannot be a prime.
See also