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?
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
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)))]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With