Understanding the result of modulo operator: %%

Nothing wrong:

10 = 1 * 10 + 0
20 = 2 * 10 + 0
10 = 0 * 20 + 10
2  = 0 * 8  + 2 

The modulo is the number after +.


In general, for two numbers a and b, there is

a = floor(a / b) * b + (a %% b)

Let’s write a toy function:

foo <- function(a,b) c(quotient = floor(a / b), modulo = a %% b)

foo(10, 10)
#quotient   modulo 
#   1        0 

foo(20, 10)
#quotient   modulo 
#   2        0 

foo(10, 20)
#quotient   modulo 
#   0       10 

foo(2, 8)
#quotient   modulo 
#   0        2 

Update: Instead of using floor(a / b) to get quotient, we can also use a %/% b.

Leave a Comment