โ๏ธremainder vs. modulo vs. mod
๐ง under construction
JS โฉ operator โฉ arithmetic โฉ remainder vs. modulo
r
=
a
-
b
*
q
where๏ผ
a % b๏ผ
r
has the same sign asa
.modulo(a, b)๏ผ
r
has the same sign asb
.mod(a, 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
Was this helpful?