階乗その3

再帰の勉強

#Ruby
def fact(n)
  def fact_loop(n, i=1, p=1)
    if i > n then p
    else fact_loop(n, i+1, p*i)
    end
  end
  fact_loop(n)
end
puts fact(5) #=>120
//Scala
def fact(n: Int):Int={
  def factLoop(n: Int, i: Int, p: Int):Int = if (i > n) p else fact_loop(n, i+1, p*i)
  factLoop(n,1,1)
}
println(fact(5)) //=>120