-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?

6
  • 1
    By what logic would you expect to get 4? Commented Jul 22, 2017 at 14:02
  • @torazaburo google logic: google.com/… Commented Jul 22, 2017 at 14:03
  • 1
    The number -1 is equal to 4 (modulo 5). Commented Jul 22, 2017 at 14:04
  • @Pointy I must not understand basic math. The fact remains that JS results != google arithmetic results. Commented Jul 22, 2017 at 14:09
  • 1
    As the wiki article linked from the duplicate states programming languages vary in how negatives are treated en.m.wikipedia.org/wiki/Modulo_operation Commented Jul 22, 2017 at 14:11

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.