Edansys

My WordPress Blog

Feb

22

Factorial in multiple languages


Languages that I like to dabble in:

Clojure

(defn fact [n]
  (apply * (range 2 (inc n))))

Scala

def fact(x: BigInt): BigInt = if (x == 0) 1 else x * fact(x - 1)

JavaScript

function fact(n) {
   return (n == 0) ? 1 : n * fact(n - 1);
}

Groovy

def fact(n) {
    (2..n).inject(1) { fact, i | fact * i }
}

Python / Jython

def fact(x): return (1 if x==0 else x * fact(x-1))

Ruby

def fact(n)
  (1 .. n).inject{|a, b| a*b}
end

Leave a Reply