Skip to content

clojure.core/mod

View this page on ClojureDocs

Type: function Added: Clojure 1.0 Examples: 3 Runnable: 3
([num div])

Modulus of num and div. Truncates toward negative infinity.

Examples

by zk on
by dijonkitchen on
by betegelse on

Note by wdkrnls

The difference between rem and mod can be remembered by noting that mod always returns a value between 0 and div.

Note by kingcode

I am confused by the comment about the definition on lines 13+ of the example - which is not accurate when invoking mod when 'num' is positive and 'div' negative. Applying the definition to

(mod 10 -3)
we have

  • the largest multiple of -3 not exceeding 10 is 9, from using -3 as a multiplier
  • however (mod 10 -3) yields -2, meaning that 10 exceeds the largest multiple not greater than 10 by -2 i.e. 10 - -2 = 12 is the largest multiple <= 10, a contradiction.
  • therefore (mod 10 -3) should yield 1, not -2
  • So unless I misunderstood, the definition should be changed to something like:

    "The mod function is defined as the amount by which a number exceeds the largest integer multiple of the divisor that is not greater than that number, except when the number is positive and the divisor negative, in which case the result is the amount by which the number exceeds the smallest multiple that is not smaller than the number."

    Or, change the implementation to something similar to:

    (defn mod-2
          [num div]
          (let [m (rem num div)]
            (if (or (zero? m) (= (pos? num) (pos? div)))
                m
                (if (pos? div) (+ m div) m)))) 
    

    to fit the current definition.

    See also


    Content from the matching ClojureDocs page, with authors credited on each contribution.