fork(2) download
  1. (defn fact [x]
  2. (loop [n x prod 1] ;; this works just like a 'let' binding.
  3. (if (= 1 n) ;; this is the base case.
  4. prod
  5. (recur (dec n) (* prod n)))))
  6.  
  7. (println (fact 5)) ;; change 5 to whatever number you like!
  8.  
  9. ;; ...but not more than 20, or you'll get an integer overflow error.
  10. ;; to fix this, you can add 'N' to the end of any number to make it a bigint.
  11. ;; 21 -> 21N
  12.  
  13. (defn fact-no-loop [n]
  14. (if (= 1 n)
  15. 1
  16. (* n (fact-no-loop (dec n)))))
  17.  
  18. (println (fact-no-loop 5)) ;; still works!
  19.  
  20. (time (fact 20))
  21.  
  22. (time (fact-no-loop 20))
  23.  
Success #stdin #stdout 1.99s 335488KB
stdin
Standard input is empty
stdout
120
120
"Elapsed time: 0.227279 msecs"
"Elapsed time: 0.218576 msecs"