⚖️remainder vs. modulo vs. mod

🚧 under construction

JSoperatorarithmetic ⟩ remainder vs. modulo

r=a-b*q where:

  • a % br has the same sign asa.

  • modulo(a, b)r has the same sign asb.

  • mod(a, b)0r<b0 \le r<|b| (remainder in math)

replit: modulo(a,b) vs. mod(a,b)

// ⭐️ modulo: r = a - b*q
// ------------------------
// • r has same sign as b.
//   (that is, `b` decides the "sign" of the result)
function modulo(a, b) {
    return ((a % b) + b) % b
}

// ⭐️ mod: r = a - b*q
// ------------------------
// • 0 <= r < |b| (remainder in math)
function mod(a, b) {
    b = Math.abs(b);
    return ((a % b) + b) % b;
}

💈範例:

// remainder (a % b)
//┌─── `a` decides the "sign" ⭐️
//│
  5 %  3,    //  2
  5 % -3,    //  2
 -5 %  3,    // -2
 -5 % -3,    // -2

// modulo(a, b)
//          ┌─── `b` decides the "sign" ⭐️
//          │ 
modulo( 5,  3),    //  2
modulo( 5, -3),    // -1
modulo(-5,  3),    //  1
modulo(-5, -3),    // -2

modulo(6.4, 2.3),     //  1.8000000000000007

// mod(a, b) (in math)
//                    ┌─── always >= 0 ⭐️
//                    │ 
mod( 5,  3),       // 2
mod( 5, -3),       // 2
mod(-5,  3),       // 1
mod(-5, -3),       // 1

Last updated