Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i solve integer overflow in Clojure?

Tags:

clojure

I am doing this exercise. Pascal's Trapezoid

My solution is:

(fn pascal[initseq]
  (let [gen-nextseq (fn [s]
                      (let [s1 (conj (vec s) 0)
                            s2 (cons 0 s)]
                        (map + s1 s2)))]
    (cons 
      initseq 
      (lazy-seq 
        (pascal 
          (gen-nextseq initseq))))))

I passed first three test cases, but failed the last one.

It says "java.lang.ArithmeticException: integer overflow"

So, is there a big integer in Clojure, or is there a better way to solve the problem?

like image 367
yehe Avatar asked Aug 28 '26 11:08

yehe


2 Answers

Change + to +'. That will automagically get you a clojure.lang.BigInt if the result doesn't fit into a long. You can also use the N suffix on literals to get a BigInt.

(class (+' 3 2)) ;=> java.lang.Long
(class (+' 300000000000000000000000000000 2)) ;=> clojure.lang.BigInt
(class 3N) ;=> clojure.lang.BigInt
like image 189
Cubic Avatar answered Aug 30 '26 02:08

Cubic


You can use +' instead of + for arbitrary precision.

(fn pascal[initseq]
  (let [gen-nextseq (fn [s]
                      (let [s1 (conj (vec s) 0)
                            s2 (cons 0 s)]
                        (map + s1 s2)))]
                             ^^
...

So you can modify the above marked potion of the code as follow.

                        (map +' s1 s2)))]
like image 30
ntalbs Avatar answered Aug 30 '26 03:08

ntalbs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!