Difference between mod and rem in Clojure - clojure

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

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

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.

The difference shows up with negative numbers. (rem -3 2) is -1, while (mod -3 2) is 1.
More generally, the rem function is defined to complement quot, which is integer division rounding toward zero. So this relation always holds:
(let [q (quot a b)
r (rem a b)]
(assert (= a (+ r (* q b)))))
For example, (quot -3 2) is -1, (rem -3 2) is -1, and (+ -1 (* -1 2)) is indeed -3.
The mod function is instead defined such that the result of (mod a b) for positive b is always in the range [0,b-1], even if a is negative. This is normally what you expect from "modular arithmetic"; a repeating cycle of the same numbers forever, no matter which direction you go in.
It's especially useful in conjunction with an integer division operation which rounds down instead of toward zero (that is, if the answer is negative, the rounded answer is more negative), which Clojure unfortunately doesn't have a predefined function for. You can define your own, though:
(defn div [a b] (int (. Math floor (/ a b))))
Then (div -3 2) is -2, because -2 * 2 = -4 is the largest even multiple of 2 less than or equal to -3. (Equivalently, -2 is the largest integer less than or equal to -1.5.)
This is in fact how integer division is defined in many other languages, such as Common Lisp (the two-argument floor function), Python (the // operator), Ruby (the Integer#div method), etc.
With such a function defined, the above assertion for quot/rem also holds for div/mod:
(let [q (div a b)
r (mod a b)]
(assert (= a (+ r (* q b)))))
For example, (div -3 2) is -2, (mod -3 2) is 1, and (+ 1 (* -2 2)) is again equal to -3.

Related

Creating a sequence of all values in Clojure

I'm currently working on a kata code challenge and it comes with a few requirements:
The number u(0) = 1 is the first one in u.
For each x in u, then y = 2 * x + 1 and z = 3 * x + 1 must be in u too.
There are no other numbers in u.
I have constructed a few functions:
(defn test2 [x n orgN] ;;x is a counter, n is what I want returned as a list
(println n)
(println "this is x: " x)
(cons n (if (not= x (- orgN 1 ))
(do (test2 (+ x 1) (+ 1 (* n 2)) orgN)
(test2 (+ x 1) (+ 1 (* n 3)) orgN))
nil)
))
(defn test2helper [n]
(def x 1)
(test2 x x n)
)
(test2helper 5)
However this only returns (1 4 13 40) and misses a whole bunch of values in between. Cons is only constructing a list based on the last 3n+1 algorithm and not picking up any other values when I want instead a sequence of the two values generated from each n value repeated. My question is is there a way to construct a sequence of all the values instead of just 4 of them?
https://www.codewars.com/kata/twice-linear/train/clojure
This solution is pretty close to being correct. But remember that do is for performing side effects, not for producing values. Specifically, (do x y) returns y after performing the side effects in x. But test2 does not have any side effects: it just returns a list. What you are looking for is instead (concat x y), a function which concatenates two lists together into a larger list.
Although Alan Malloy's solution answers your question, it does not solve the problem you refer to, which requires that the sequence is generated in increasing order.
My approach would be to generate the sequence lazily, according to the following pattern:
(defn recurrence [f inits]
(map first (iterate f inits)))
For example, you can define the Fibonacci sequence like this:
(defn fibonacci []
(recurrence (fn [[a b]] [b (+ a b)]) [1 1]))
=> (take 10 (fibonacci))
(1 1 2 3 5 8 13 21 34 55)
The sequence you need is harder to generate. Good hunting!

How to build a lazy sequence of perfect number in Clojure?

I tried to find a list of perfect number in this way:
(defn classify [num]
(let [factors (->> (range 1 (inc num))
(filter #(zero? (rem num %))))
sum (reduce + factors)
aliquot-sum (- sum num)]
(cond
(= aliquot-sum num) :perfect
(> aliquot-sum num) :abundant
(< aliquot-sum num) :deficient)))
(defn is-p [n]
(= :perfect (classify n)))
(defn list-perfect [n]
(filter is-p (range 1 (inc n))))
Question:
How to build a lazy sequence of perfect numbers, so that I can use (take n ...) to easily get a list.
Is this code idiomatic and efficient? Any improvement?
Thanks in advance.
Your algorithm is very inefficient, it's O(n).
For a quick win, you can immediately reduce the range by a half, as you won't ever have factors that are greater than the number you're testing divided by 2.
So change it to:
(defn classify [num]
(let [factors (->> (range 1 (max 2 (inc (quot num 2))))
;; ...
However... you can change it to O(sqrt n) which is magnitudes faster. See my timings below.
The real efficiency is noticing that factors are in pairs of [x (quot num x)] and then only check the first (sqrt num) (or slightly over):
(defn perfect? [n]
(let [r (range 2 (+ 2 (int (Math/sqrt n))))
s (set (mapcat #(if (zero? (rem n %))
[% (quot n %)])
r))
t (reduce + 1 s)]
(= n t)))
I've split it into separate calculations so you can verify each stage.
The range can be reduced from 2..((sqrt n) + 2), and initialise the reduction with 1 (which is always a factor).
This changes the problem from an O(n) to O(sqrt n), so if you're checking large numbers, makes a vast difference.
As an illustration here are some times on larger values for n on my MBP:
n "n/2" "sqrt n"
33550336 1,172.5ms 2.85ms
8589869056 274,346.6ms 16.76ms
137438691328 didn't time 44.27ms
so using root version was 16,369 times faster for the 6th perfect number. See http://en.wikipedia.org/wiki/List_of_perfect_numbers for more details.
EDIT:
Why (int (root n)) + 2? And why `[x (quot n x)]?
When you work out the factors of a number n, then if you find one (say, a), then n/a is also a factor (call it b) because n = a * b
e.g. looking at 28, the first relevant factor is 2, and clearly 28/2 = 14 is also a factor. So you don't need to check 14, you already know it's a factor from the fact that 2 is.
as we're incrementally checking numbers from 2 upwards, we're incidentally finding the higher numbers coming down:
2 is a factor, 28 / 2 = 14 -> [a, b] = [2, 14]
4 is a factor, 28 / 4 = 7 -> [a, b] = [4, 7]
7 is a factor, 28 / 7 = 4 -> [a, b] = [7, 4] - wait a minute...
The [a,b] pairs here are the [% (quot n %)] in the mapcat function, e.g. when the range is currently iterating the value 2, then % is 2 inside the fuction, and so (quot n %) is (quot 28 2) which is 14, thus [% (quot n %)] is simply the vector [2 14], which then gets added to the set after being flattened to 2 and 14 as values. Later, when the range value is 4, then [% (quot n %)] is [4 (quot 28 4)] which is [4 7], and again is flattened by mapcat as the numbers 4 and 7.
So we add each pair of numbers (flattened via mapcat) to our set, include the number 1, and end up with #{1 2 14 4 7}, which are the factors of 28. (Actually, I don't put 1 in the set as I don't need to, instead I start the summing reduction at 1, which is same effect).
But at what point do they turn around? i.e. when do we know that [7,4] will already have been included in the set as [4,7]?
clearly it's when a > b, because in finding the lowest numbers we always find the highest number with it, so we can finish checking at this point.
but what is this point? it's simple, if a perfect number were a square number, then a and b would be equal, i.e. a*a = n, so a = sqrt(n).
Thus the highest value of a we need to check is the whole number that is larger than the root of n.
e.g. for 28, sqrt(28) = 5.292, so we have to check 6 to be sure that we've included the lowest number possible that could be a factor that has a paired factor.
so we need (int (sqrt n)) + 1.
I always do this in case the root calculation is 1.9999999999... and rounds wrong way, so adding 1 more ensures you eliminate any rounding errors.
but in a range, if you want to include that number you have to add 1 more to it (range drops the high number, (range 6) = (0 1 2 3 4 5)), hence why it adds 2 to the value: 1 for the range, 1 to ensure it's above the rounded down root.
Although, after saying this, I've tested perfect numbers up to 2305843008139952128 and it works with +1 instead of +2, not that it's a massive saving. Probably because non of the perfect numbers are close to perfect squares in ones I checked, so there's no rounding error in (int (sqrt n)).
If you're interested in perfect numbers, I'd recommend reading http://britton.disted.camosun.bc.ca/perfect_number/lesson1.html
list-perfect is already lazy due to your usage of filter:
(filter pred coll)
Returns a lazy sequence of the items in coll for which
(pred item) returns true. pred must be free of side-effects.
Whether code is idiomatic or not might be a matter of opinion (and hence off-topic), but it looks good enough from my perspective.

my Modulo Inverse in clojure Seems to give wrong answer

Hi I am programming in clojure and though the problem of modulo inverse has nothing to do with language i am stuck at this code -
(defn EulerDiv [x p]
(let [ToMod (+ p 2)]
(loop [num 1 toPow (int p) numDouble x]
(if (= 0 toPow)
num
(let [numDouble2 (rem (* numDouble numDouble) ToMod)
halfToPow (int (/ toPow 2))]
(if (odd? toPow)
(recur (rem (* num numDouble) ToMod)
halfToPow
numDouble2)
(recur num halfToPow numDouble2))
))))
)
It seems to give me right answers for small Primes but when i am using it in a problem with Bigger primes i am getting answers other than result like :
(= 2 (mod (* 4 (EulerDiv 2 (- 3 2))) 3))
This prints true
(def ToMod (+ 10e8 7))
( = 1 (int (mod (* 2 (EulerDiv 2 (- ToMod 2))) ToMod)) )
This prints false.
Also there is rem and mod in clojure.
mod makes the output positive and hence i can not use it in between the calculations.
It is a programming contest but this is just part of solution and this info of modulo inverse was also provided in the problem page.
The problem is that of programming calculator grammar for evaluating evpressions like 4/-2/(2 + 8)
You are straying from integer arithmetic.
Given integers, the / function can produce rationals: (/ 1 2) is 1/2, not 0.
And 1e9 is 1.0E9, a double, not an integer.
There are appropriate substitutes available. Look at the arithmetic section here for an integer division function, and at the cast section for something to convert a number to an integer.
All the best!

How does Clojure produce a positive value when a negative value is passed to this abs function?

It has been nagging me as to how cond returns a positive value in function, when a negative value is passed to its x parameter. My idea is that two negatives multiplied produce a positive, but this seems quite confusing as there appears to be no multiplication occurring anywhere in the function.
Could someone give me an detailed explanation of why a negative value passed to x returns a positive value?
(def abs
(fn [x]
(cond (> x 0) x
(= x 0) 0
(< x 0) (- x))))
(abs -10) -> 10
The code is a variation of the abs function found in the book SICP, but written in Clojure.
Kind regards
When the number is negative, (< x 0), we negate it, (- x), to get a positive number of the same magnitude. You can think of negation as multiplication by -1 if you like.
(doc -)
-------------------------
clojure.core/-
([x] [x y] [x y & more])
If no ys are supplied, returns the negation of x, else ...

Solving Project Euler 1

I am trying to solve Project Euler problem in Clojure using recursion. The following is the problem statement:
If we list all the natural numbers below 10 that are multiples of 3 or
5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
However, the code below seems to give the wrong answer. What am I doing wrong?
(defn m?
[x]
(or (= (rem x 3)) (= (rem x 5))))
(defn sum-m
[limit sum]
(if (= limit 0)
sum
(recur (dec limit)
(if (m? limit)
(+ sum limit)
sum))))
(sum-m (dec 1000) 0)
You didn't say what erroneous answer it was giving, but I believe the problem is in m?:
(or (= 0 (rem x 3)) (= 0 (rem x 5)))
m? change to
(defn m? [x]
(or (zero? (rem x 3))(zero? (rem x 5))))
I think you wanted the function m? to check if a number is multiple of 3 or 5. But it does not do that. You should check if any of (rem x 3) or (rem x 5) are zero.
It's an interesting exercise to solve this for very large numbers. For example, find the sum of all the natural numbers below 1 billion that are multiples of 3 or 5. Your solution is linear in time, but you can try for a solution that is faster. This is not part of your original question; just an interesting addition to it.