Skip to content

Instantly share code, notes, and snippets.

@danielef
Created July 30, 2016 18:50
Show Gist options
  • Save danielef/a2131eeb0e796394258f7b6c136acc7d to your computer and use it in GitHub Desktop.
Save danielef/a2131eeb0e796394258f7b6c136acc7d to your computer and use it in GitHub Desktop.
Factorial & Fibonnaci en Clojure
;; Factorial Recursivo
;; http://stackoverflow.com/questions/1662336/clojure-simple-factorial-causes-stack-overflow
(defn !-recursive [x]
(if (= x 1) 1N
(* x (!-recursive (dec x)))))
;; Factorial Iterativo
;; https://mitpress.mit.edu/sicp/full-text/sicp/book/node15.html
(defn !-iterative
([x] (!-iterative 1N 1 x))
([acc i x] (if (> i x) acc
(!-iterative (* i acc) (inc i) x))))
;; Factorial Loop/Recur
;; https://clojuredocs.org/clojure.core/loop
(defn !-loop [x]
(loop [i x acc 1N]
(if (= i 1) acc
(recur (dec i) (* acc i)))))
;; Factorial Reduce
;; http://stackoverflow.com/questions/1662336/clojure-simple-factorial-causes-stack-overflow
(defn !-reduce [x]
(reduce * (range 1N (inc x))))
;; Fibonacci 1
;; http://stackoverflow.com/questions/8939970/a-recursive-fibonacci-function-in-clojure
(defn fib1
([n] (fib1 [0 1] n))
([x, n] (if (>= (count x) n) x
(recur (conj x (apply + (take-last 2 x))) n))))
;; Fibonacci 2
;; http://c2.com/cgi/wiki?FibonacciSequence
(defn fib2[n]
(loop [m 0 k 1 i n x []]
(if (= i 0) x
(recur k (+ m k) (- i 1) (conj x m)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment