Home>

### c # - i can't understand the if statement of the primality test program

When I was building a program to judge whether the number entered using c # is a prime number, there was a part that I could not understand by all means, and even if I looked it up, I could only find the code using c language or c ++, so I will ask you a question.

``````class Program
{
static void Main (string [] args)
{
int num = int.Parse (Console.ReadLine ());
int i;
for (i = 2;i<= num/2;i ++)
{
if ((num% i) == 0)
{
break;
}
}
if (i>(num/2))
{
Console.WriteLine ("{0} is a prime number", num);
}
else else
{
Console.WriteLine ("{0} is not a prime number", num);
}
}
}``````

I can understand up to the point of exiting the for statement, but I can't understand that (num/2) becomes smaller than i in the subsequent if (i>(num/2)). Since the initial expression of the for statement defines i<= num/2, we can see that they are equal, but why is it so small?

Since the initial expression of the for statement defines i<= num/2, we can see that they are equal, but why is it so small?

Since that is the "continuation condition" of the for statement, while that condition is satisfied`i`The value of will continue to increase by 1. Eventually,`i`The value of is the first value that the continuation condition does not hold`num/2 + 1`To reach.

However, the condition of the if statement in the for statement (`num% i == 0`) Is established`i`The value of`num/2`Escape from repetition even if:

In other words, when the for statement ends`i`The value of is divided into the value when it is repeated until the end without escaping and the value when it escapes in the middle.

Therefore, in the if statement after the for statement,`i`We check which value the value corresponds to and determine whether it is a prime number or not.

for statement isWhile the condition of the second equation is metWill be executed repeatedly.
In other words, exiting for by means other than forced means such as break meansThe condition of the second equation is not satisfiedIt means that it has become.
`i<= num/2`Is not satisfied, that is`i>num/2`about it.

``````if (i>(num/2))