如何计算红宝石中的阶乘

时间:2014-04-25 16:31:48

标签: ruby factorial

问题

Input:
  4 # number of input 
  1
  2
  4
  3
Output:
  1
  2
  24
  6

无法获得所需的输出

My code:
num  = Integer(gets.chomp)
k = []
for i in 1..num
k[i] = Integer(gets.chomp)
end

k.each do |w|
for i in 1..w
w.to_i = w*i
end
puts w 
end

2 个答案:

答案 0 :(得分:1)

获得n

的阶乘
(1..n).inject :*

照顾零

(1..n).inject(1, :*)

答案 1 :(得分:0)

您可以尝试:

input = Integer(gets.chomp) 
ans = 1
for i in 1..input
 ans = ans*i
end
print(ans)