# modulo(a, b)

[JS](https://lochiwei.gitbook.io/web/js) ⟩ [operator](https://lochiwei.gitbook.io/web/js/grammar/op) ⟩ [arithmetic](https://lochiwei.gitbook.io/web/js/grammar/op/arithmetic) ⟩ modulo

{% hint style="success" %} <mark style="color:purple;">modulo</mark>(<mark style="color:yellow;">a</mark>, <mark style="color:yellow;">b</mark>) returns the [modulo](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Remainder#description) of <mark style="color:yellow;">a / b</mark>. (<mark style="color:yellow;">b</mark> decides the <mark style="color:red;">**sign**</mark> of the modulo)

(:point\_right: see [remainder-vs.-modulo-vs.-mod](https://lochiwei.gitbook.io/web/js/grammar/op/arithmetic/binary/remainder/remainder-vs.-modulo-vs.-mod "mention") for more info)
{% endhint %}

{% tabs %}
{% tab title="💾 程式" %}

* replit： [modulo(a,b) vs. mod(a,b)](https://replit.com/@pegasusroe/modulo-moda-b#index.js)

```javascript
// ⭐️ 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
}
```

💈範例：

```javascript
// 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
```

{% endtab %}

{% tab title="⭐️ 重點" %}
{% hint style="warning" %}
:star: <mark style="color:purple;">**remainder (%)**</mark> and [<mark style="color:blue;">**modulo**</mark>](https://lochiwei.gitbook.io/web/js/grammar/op/arithmetic/binary/remainder/modulo) <mark style="color:yellow;">**are**</mark>**&#x20;**<mark style="color:red;">**different**</mark>:exclamation:\
:point\_right: [remainder-vs.-modulo-vs.-mod](https://lochiwei.gitbook.io/web/js/grammar/op/arithmetic/binary/remainder/remainder-vs.-modulo-vs.-mod "mention")
{% endhint %}
{% endtab %}

{% tab title="👥 相關" %}

* :point\_right:[](https://lochiwei.gitbook.io/web/js/grammar/op/arithmetic/binary/remainder "mention")
* :scales:[remainder-vs.-modulo-vs.-mod](https://lochiwei.gitbook.io/web/js/grammar/op/arithmetic/binary/remainder/remainder-vs.-modulo-vs.-mod "mention")
  {% endtab %}

{% tab title="📗 參考" %}

* [ ] [javascript-the-definitive-guide](https://lochiwei.gitbook.io/web/master/ref/javascript-the-definitive-guide "mention") ⟩ 4.8&#x20;
  {% endtab %}

{% tab title="📘 手冊" %}

* [Remainder (%)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Remainder)
  {% endtab %}
  {% endtabs %}
