• (mod num div)
Modulus of num and div. Truncates toward negative infinity.

1 Example top

  • user=> (mod 10 5)
    0
    
    user=> (mod 10 6)
    4
    
    user=> (mod 10 10)
    0
    
    user=> (mod 10 -1)
    0
    
    ;; 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.
    ;; The largest integer multiple of 5 not greater than -2 is 5 * -1 = -5. The amount by which -2 exceeds -5 is 3. 
    ;;
    user=> (mod -2  5) 
    3
    
Log in to add / edit an example.

See Also top

Log in to add a see also.

Plus_12x12 Minus_12x12 Source clojure/core.clj:3159 top

(defn mod
  "Modulus of num and div. Truncates toward negative infinity."
  {:added "1.0"
   :static true}
  [num div] 
  (let [m (rem num div)] 
    (if (or (zero? m) (= (pos? num) (pos? div)))
      m 
      (+ m div))))
Vars in clojure.core/mod:
Used in 0 other vars

Comments top

1 comment(s) for mod.

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.

    Log in to add a comment.