Search code examples
roperators

Understanding the result of modulo operator: %%


I'm trying to understand how the %% operator works in R:

10 %% 10  # 0
20 %% 10  # 0

I'm not sure about these two results:

10 %% 20  # 10
2 %% 8  # 2

Can you help me understand the last two results? I'm a little confused.


Solution

  • 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.