How to get the remainder of an integer division operation?

    2 answers 2

    very simple

    if (x % t != 0) { cout << "при делении x на t есть остаток" << endl; } else { cout << "остатка нет" << endl; } 

      From a mathematical point of view , the operation of calculating the remainder in C / C ++ for negative numbers, for example -11 % 8 == -3 , gives the wrong result to which we are accustomed from school. Of course, this is a matter of agreement , but ... This problem sometimes causes confusion and heated debate .

      If the task is to determine only the absence of a residue, then % sufficient. However, there is a particular solution when the divisor is a number of degree 2. The same method is the easiest to determine the remainder of dividing by numbers greater than 1 equal degrees 2.

       int a; int b; //2 в степени n if (a & (b - 1)) //остаток от деления присутствует. Например, -11 & (8 - 1) == 5 else //остаток равен нулю. Например, -8 & (8 - 1) == 0 

      Why is it important? Consider the sequence mod(n, 4)

      For n & (4-1) the sequence is periodic

        n -8 -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7 8 n&3 3 * * * * 2 * * * * 1 * * * * 0 * * * * * 

      For n% 4, the sequence is, generally speaking, non-periodic

        n -8 -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7 8 n%4 3 * * 2 * * 1 * * 0 * * * * * -1 * * -2 * * -3 * * 

      Working with a periodic sequence is much more pleasant where it is necessary to observe equal intervals between events. You can build a type design

       switch (i & 3) { case 0: /*событие 1*/; break; case 1: /*событие 2*/; break; case 2: /*событие 3*/; break; case 3: /*событие 4*/; break; } 

      and to be sure that each event will occur with an enviable regularity, regardless of the sign i and additional case not required.

      • Excuse me, why did you decide that the question is about negative numbers? - Kromster
      • one
        @Kromster, probably played the role of the number of votes of the question :) - αλεχολυτ
      • @Kromster, And why not? The range is not specified in the question, and KoVadim gave a version that may not be optimal in some cases. Again, my answer provides an alternative solution and explains why, is it bad? - mr NAE