-1

I have the following:

-1 mod 5

I expect to get 4.

However in JS (-1 % 5), I'm getting -1.

What am I doing wrong?

SB2055
  • 12,272
  • 32
  • 97
  • 202
  • 1
    By what logic would you expect to get 4? –  Jul 22 '17 at 14:02
  • @torazaburo google logic: https://www.google.com/search?q=-1+mod+5&rlz=1C1CHZL_enUS749US749&oq=-1+mod+5&aqs=chrome.0.69i59.2215j0j1&sourceid=chrome&ie=UTF-8 – SB2055 Jul 22 '17 at 14:03
  • 1
    The number -1 is equal to 4 (modulo 5). – Pointy Jul 22 '17 at 14:04
  • @Pointy I must not understand basic math. The fact remains that JS results != google arithmetic results. – SB2055 Jul 22 '17 at 14:09
  • 1
    As the wiki article linked from the duplicate states programming languages vary in how negatives are treated https://en.m.wikipedia.org/wiki/Modulo_operation – Martin Smith Jul 22 '17 at 14:11
  • You can always just add 5 if the result is negative. Highly recommend Underwood Dudley's classic [*Elementary Number Theory*](https://www.amazon.com/Elementary-Number-Theory-Second-Mathematics/dp/048646931X) – Pointy Jul 22 '17 at 14:19

1 Answers1

1

mod is the leftover when you divide the number by the divider.

In Math -1%5 = -1 so Js is working as expected.

You are not doing anything wrong. If you want to get a positive number (the difference) add the divider number to the result.

var result = (-1 % 5) + 5;

It doesn't matter where you add the number before the module or after. Its a pure math.

CodeWizard
  • 128,036
  • 21
  • 144
  • 167
  • 1
    https://www.google.com/search?q=-1+mod+5&rlz=1C1CHZL_enUS749US749&oq=-1+mod+5&aqs=chrome.0.69i59.2215j0j1&sourceid=chrome&ie=UTF-8 – SB2055 Jul 22 '17 at 14:01