Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between mod and rem in Clojure

I could not understand the difference between these two (mod & rem) functions.

like image 511
Ertuğrul Çetin Avatar asked May 13 '16 13:05

Ertuğrul Çetin


People also ask

What is difference between mod and REM?

Description: mod and rem are generalizations of the modulus and remainder functions respectively. mod performs the operation floor on number and divisor and returns the remainder of the floor operation. rem performs the operation truncate on number and divisor and returns the remainder of the truncate operation.

What Is REM in Haskell?

rem is integer remainder, satisfying: (x `quot` y)*y + (x `rem` y) == x. div is integer division truncated toward negative infinity.


2 Answers

Clojuredoc's example for rem describes the difference:

;; rem and mod are commonly used to get the remainder.
;; mod means Gaussian mod, so the result is always
;; non-negative.  Don't confuse it with ANSI C's %
;; operator, which despite being pronounced
;; 'mod' actually implements rem, i.e. -10 % 3 = -1.

user=> (mod -10 3)
2

user=> (rem -10 3)
-1
like image 83
Piotrek Bzdyl Avatar answered Sep 21 '22 08:09

Piotrek Bzdyl


mod returns the difference of the first number, and the biggest integer (possibly negative) multiple of the second number that is less than the first number:
rem is just the remainder.

For example (rem -4 3) => -1 no surprise here: -4 divided by 3 is -1 with -1 "left over".
But weirdness happens if we use mod: (mod -4 3) => 2:

  • The greatest integer multiple of 3 less than -4 is -6.
  • -4 minus -6 is 2.

So even though they usually act similarly, mod does not return the remainder, it does something more specific.

You might find these clojuredocs examples helpful.

like image 32
Adam Lee Avatar answered Sep 21 '22 08:09

Adam Lee