Created
April 17, 2012 18:48
-
-
Save andersonvom/2408158 to your computer and use it in GitHub Desktop.
SPOJ 011 - Factorial
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def z_naive(n) | |
temp = 1 | |
num_zeroes = 0 | |
(2..n).each do |i| | |
temp *= i | |
while temp%10 == 0 | |
temp /= 10 | |
num_zeroes += 1 | |
end | |
end | |
num_zeroes | |
end | |
# Zeroes are only added when five multiplies [2,4,6,8] | |
# and zeroes are added for every power of 5 that multiplies | |
# these numbers. | |
def z(n) | |
power = 5 | |
num_zeroes = 0 | |
while power <= n | |
num_zeroes += n/power | |
power *= 5 | |
end | |
num_zeroes | |
end | |
# Run all test cases | |
if __FILE__ == $0 | |
while tests = gets | |
tests = tests.to_i # around 100_000 | |
tests.times do |i| | |
n = gets.to_i # <= 1_000_000_000 | |
puts z n | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment