Home>

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?

c#
  • Answer # 1

    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 satisfiediThe value of will continue to increase by 1. Eventually,iThe value of is the first value that the continuation condition does not holdnum/2 + 1To reach.

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

    In other words, when the for statement endsiThe 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,iWe check which value the value corresponds to and determine whether it is a prime number or not.

  • Answer # 2

    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/2Is not satisfied, that isi>num/2about it.

  • Answer # 3

    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?

    It is not an initialization formula. It is a conditional expression.
    When i is less than or equal to (num/2), the for loop is repeated, and when i is greater than (num/2), the for loop is terminated.

    Therefore, the following judgment is whether the for loop is repeated to the end and ended.

    if (i>(num/2))
    {
        Console.WriteLine ("{0} is a prime number", num);
    }

Related articles