Jan 17, 2008

The one line Ruby program for the factorial of n (n!)

Write a program that calculates the facctorial of n (n!).

result = n * (n - 1) * (n - 2) * ... * 2 * 1


I write a Ruby program.
n = gets.to_i
k = 1
n.times do |i|
k *= i.next
end
puts k
This is a normal program.
Let's write in one line.

k = 1
gets.to_i.times { |i| k *= i.next }
puts k
It's easy so far.


A little device.
k = 1
puts k if gets.to_i.times { |i| k *= i.next }

The key point is the initialization of a variable.
lambda { |k| puts k if gets.to_i.times { |i| k *= i.next } }.call(1)
Completion!

No comments: