Negative modulo number in fast

How does modulation of negative numbers work in fast? When I did (-1% 3), it gave -1, and the remainder is 2. What is the catch?

+10
source share
2 answers

The remainder % Swift operator calculates the remainder of the integer division:

 a % b = a - (a/b) * b 

where / is a division with truncation of integers. In your case

 (-1) % 3 = (-1) - ((-1)/3) * 3 = (-1) - 0 * 3 = -1 

Thus, the balance always has the same sign as the dividend (if only the balance is zero).

This is the same definition as required, for example. in the C99 standard; see, for example, Does ANSI C or ISO C indicate -5% 10? . See also Wikipedia: Modulo operation for an overview of how it is handled in different programming languages.

The true module function can be defined in Swift as follows:

 func mod(_ a: Int, _ n: Int) -> Int { precondition(n > 0, "modulus must be positive") let r = a % n return r >= 0 ? r : r + n } print(mod(-1, 3)) // 2 
+18
source

From the Language Guide - Basic Operators :

Stop statement

The remainder operator ( a % b ) determines how many multiples of b will be placed inside a and returns the remaining value (known as the remainder).

The remainder operator ( % ) is also known as the modulo operator in other languages. However, its behavior in Swift for negative numbers means that, strictly speaking, it is a remainder, not a modular operation .

...

The same method is used to calculate the remainder for a negative value of a:

 -9 % 4 // equals -1 

Box -9 and 4 in the equation gives:

 -9 = (4 x -2) + -1 

giving a residual value of -1 .

In your case, no 3 will match 1 , and the remainder is 1 (the same with -1 β†’ remainder -1 ).

+5
source

Source: https://habr.com/ru/post/1013212/


All Articles