static void Main(string[] args) { int i, num, factor; bool isprime; for (num = 2; num < 10; num ++) { isprime = true; factor = 0; for (i=2; i <= num/2; i++) { if ((num % i) == 0) { isprime = false; factor = i; } } if (isprime) Console.WriteLine(num + " - простое число"); else Console.WriteLine("Наибольший множитель числа " + num + " равен " + factor); } Console.ReadLine(); 

I must say that the code is working. The program receives the number num , divides it by i , according to the condition and displays that the number is num :

  1. Prime number
  2. The largest factor of num is i

Now the question is: why is the value of isprime first taken to be true , then false and in the if takes true , although (if you take the number 2) it turns out that the last if includes isprime=false ? I'm confused.

  • @Treaq; If you are given an exhaustive answer, mark it as correct (click on the check mark next to the selected answer). - Vitalina

2 answers 2

Elementary. Actually, the isprime flag determines whether a number is simple. First, at each new iteration of the loop, you assume that the next number is prime ( isprime = true ). Then, if your number is divisible by i, then the number, of course, can no longer be considered simple ( isprime = false ).

    At the beginning of the cycle, you assign the isprime variable to true. When entering the second cycle, of course, true.

    In the first iteration, the variable i = num = 2, and you divide num / i without a trace, the isprime value becomes false.

    In the second iteration, the variable i is equal to 3, and you divide 2/3, getting the remainder not equal to zero.