2

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?

2 Answers 2

8

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
Sign up to request clarification or add additional context in comments.

Comments

2

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)))]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.