标签:
1 #求阶乘方法一 2 def f1(n) 3 if n == 1 4 return 1 5 else 6 return n * f1(n-1) 7 end 8 end 9 10 #求阶乘方法二 11 def f2(n) 12 i = 1 13 while n > 0 14 i *= n 15 n -= 1 16 end 17 return i 18 end 19 20 #求1到n的阶乘之和方法一 21 sum = 0 22 (1..43).each do | x | 23 sum = sum + f2(x) 24 end 25 puts sum 26 27 #求1到n的阶乘之和方法二 28 def f3(n) 29 sum = 0 30 n.downto(1) do 31 while n > 0 32 i = 1 33 i *= n 34 n -= 1 35 sum *= i 36 sum += i 37 end 38 end 39 return sum 40 end 41 puts f3(43) 42 43
标签:
原文地址:http://www.cnblogs.com/lucien06/p/5894551.html