Clojure - Calculate with big numbers - clojure

I want to calculate !1000 in clojure, how can I do this without getting a integer-overflow exception?
My factorial code is right now: (reduce * (range 1 1001)).

You could use the *' operator which supports arbitrary precision by automatically promoting the result to BigInt in case it would overflow:
(reduce *' (range 1 1001))

Put N at the end of the number which makes it a bigint,
(reduce * (range 1N 1001N))

Coerce the parameters to clojure.lang.BigInt
(reduce * (range (bigint 1) (bigint 1001)))
I.e. if you are working with an third-party library that doesn't use *'
(defn factorial' [n]
(factorial (bigint n)))

Related

clojure: Compute Factorial of number using defmulti and defmethod

I tried to compute factorial through defmulti and defmethod.
(defmulti factorial identity)
(defmethod factorial 0 [_] 1)
(defmethod factorial :default [num]
(* num (factorial (dec num))))
It works fine for small numbers
(-> 10 factorial) ;;3628800
(-> 2 factorial) ;; 2
it shows Integer Overflow Exception for factorial 40
(-> 40 factorial)
ArithmeticException integer overflow clojure.lang.Numbers.throwIntOverflow
My curiosity is
How can we compute factorial for Big Numbers using defmulti and defmethod?
Clojure's implementation of number types builds on the host platform's number types. Your solution works when you define the arbitrary size flag N, because the underlying number type changes on the JVM.
(type 10) ;=> java.lang.Long
(type 10N) ;=> clojure.lang.BigInt
clojure.lang.BigInt uses either java.math.BigInteger or a Java long as the underlying type, depending on the bit size of the number.
On a different host, the Javascript engine of a browser, both types are JavaScript's native Numbers. The factorial function gives a result up to 170 in ClojureScript. It does not throw when overflowing, but returns the JavaScript number value Infinity:
(factorial 170) ; => 7.257415615307994e+306
(factorial 170N) ; => 7.257415615307994e+306
(factorial 171N) ; => Infinity
Update: This answer (pointed out by #cske) gives a neat solution to use the *' operator, which bumps up the number type in case it would overflow:
(defmethod factorial :default [num]
(*' num (factorial (dec num))))
(factorial 40) ; => 815915283247897734345611269596115894272000000000N
I have solved it
(-> 40N factorial) ;;815915283247897734345611269596115894272000000000N

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!

More functional way to do this?

This post of mine discusses Thomson's paradox, and simulates it in Clojure.
The state function returns the state of the lamp at time = t.
(defn thomsons-lamp []
(iterate (fn [[onoff dur]]
[(not onoff) (/ dur 2)])
[true 1]))
(defn state [t]
(let [t-vals (map second (thomsons-lamp))]
(loop [i 1]
(if (<= t (apply + (take i t-vals)))
((comp first last) (take i (thomsons-lamp)))
(recur (inc i))))))
How do I define a cleaner state function (preferably without loop/recur)?
The only sins here are
Unnecessary quadratic complexity in state
Evidence of floating point usage and error in your blog post. The code as written should be using ratios -- (state 2) should not terminate...
Reduce/reduced would be a good candidate for your state function.
(defn thomsons-lamp []
(map vector (iterate not true) (iterate #(* 1/2 %) 1)))
(defn state [t]
(reduce (fn [[s1 t1] [s2 t2]]
(if (>= t1 t) (reduced s1) [s2 (+ t1 t2)]))
(thomsons-lamp)))
A one-line solution in Clojure
In Clojure, though not in ClojureScript, we can express the state function as a series of pure function applications:
(defn state [t]
(-> t rationalize / biginteger .bitLength odd?))
or, without using the threading macro
(defn state [t]
(odd? (.bitLength (biginteger (/ (rationalize t))))))
Let's test it:
(map (juxt identity state) [1 0.7 0.5 0.4 0.3 0.2])
; ([1 true] [0.7 true] [0.5 false] [0.4 false] [0.3 false] [0.2 true])
Taking it step by step:
(defn state [t]
(-> t
rationalize ; convert to a ratio to avoid losing precision using floating point
/ ; take the reciprocal
biginteger ; round down (if need be) to a java.math.BigInteger
.bitLength ; take its length in bits (a method, not a Clojure function)
odd? ; ask whether odd
))
How does it work?
Instead of testing where the given number t fits in the series of toggle-points
1 1/2 1/4 1/8 ...
we test where 1/t (that's (/ t) in Clojure) fits in the series of inverted toggle-points
1 2 4 8 ...
which, in binary, is
1 10 100 1000 ...
which are the smallest numbers with
1 2 3 4 ...
binary digits.
Applying BigInteger/bitLength tells us how many binary digits 1/t has - rounding down has no effect. This is the number of terms of series 1 2 4 8 ... that 1/t reaches. So the answer is whether this number is odd.

Promotion to BigDecimal doesn't happen

I'm using Clojure 1.5.1. Here is my program:
(def bricks4
(memoize (fn [n]
(cond (> 0 n) 0
(= 0 n) 1
(= 1 n) 1
:else (+ (bricks4 (- n 1))
(bricks4 (- n 2))
(bricks4 (- n 3))
(bricks4 (- n 4)))))))
(bricks4 70) throws exception:
ArithmeticException integer overflow clojure.lang.Numbers.throwIntOverflow (Numbers.java:1388)
I'm confused, because I thought Clojure will automatically promote numbers from Integer to Long and then to BigDemical.
What should I do to fix this program?
Clojure hasn't auto-promoted to bigint since 1.2, which is like...three years ago? These days the default is for better performance, but you can get the auto-promoting behavior by using +' instead of +, *' instead of *, and so on.

clojure storing vs. using a sequence in expression

Helo, In an effort to learn clojure, I have taken an interest in clojure.core functions that act on sequences. Recently, I noticed some odd behaviour and would like an explaination of the difference between the folling expressions:
What I'm trying to do is this:
user=> (reduce + (take-while (partial > 1000) (iterate inc 1)))
499500
However, when I store (iterate inc 1) with def a get an error:
user=> (def a (iterate inc 1))
#'user/a
user=> (reduce + (take-while (partial > 1000) (a)))
java.lang.ClassCastException: clojure.lang.Cons cannot be cast to clojure.lang.IFn (NO_SOURCE_FILE:0)
Could someone please explain what the difference between storing iterate inc 1 and using it directly in the expression? I know that a is a lazy sequence but am missing something...
Thank you very much for your time.
You should be doing
(reduce + (take-while (partial > 1000) a))
(a) attempts to call a, but it's not a function.