# Ruby 请问怎么用 Ruby 实现 1000！的末尾有多少个连续的 0

easonyuen · 2016年06月30日 · 最后由 thewawar 回复于 2016年07月02日 · 3141 次阅读

``````(1..1000).each do |i|
s = s * i
end
``````
``````c = 0
loop do
f = s % 10
c += 1 if f == 0
s = s / 10
break if f != 0
end
puts c #=> 249
``````

``````l = s.to_s.size
s  = s.to_s
c = 0
loop do
c += 1 if s[l] == '0'
l -= 1
break if s[l] != '0'
end

puts c #=> 249
``````

``````num = (1..1000).reduce(&:*).to_s

num.size - num.reverse.to_i.to_s.size

# 或

num[/[0]*\$/].size
``````

#3 楼 @mimosa 感谢大神的酷炫语法糖。。

``````def count_zeros(n)
zeros = 0
five = 5
while five < n
zeros += n / five
five *= 5
end
zeros
end
count_zeros(1000)
#=> 249
``````

``````n = 1000
[1,2,3,4].map{|i| n / 5 ** i}.inject(:+)
``````
``````n = 1000
n<5?0:(1..Math.log(n,5)).to_a.map{|i| n / 5 ** i}.inject(:+)
``````
``````def trailing_zeroes(n) # 尾随零
num = n / 5
num  == 0 ? 0 : num + trailing_zeroes(num)
end
``````

(foo = lambda{ |n| n / 5 == 0 ? 0 : n /5 + foo.call(n/5)}).call(1000)

``````a = (1..1000).inject(0) do |sum, num|
while(num%5==0)
sum += 1
num /= 5
end
sum
end

puts a
``````
``````1000 / 5 + 1000 / 25 + 1000 / 125 + 1000 / 625
``````