Editing Trailing zeroes in factorial

Jump to: navigation, search

Warning: You are not logged in. Your IP address will be publicly visible if you make any edits. If you log in or create an account, your edits will be attributed to your username, along with other benefits.

The edit can be undone. Please check the comparison below to verify that this is what you want to do, and then save the changes below to finish undoing the edit.
Latest revision Your text
Line 45: Line 45:
 
Functional style (Haskell):
 
Functional style (Haskell):
 
<syntaxhighlight lang="haskell">
 
<syntaxhighlight lang="haskell">
zeroes = sum . tail . takeWhile (>0) . iterate (flip div 5) -- note that 0 is an edge case
+
zeroes n = sum $ tail $ takeWhile (>0) (iterate (flip div 5) n) -- note that 0 is an edge case
 
</syntaxhighlight>
 
</syntaxhighlight>
 
Bases other than 10 may be trickier to handle. For example, consider the problem of finding the number of zeroes at the end of <math>n!</math> when expressed in base 12 (with prime factorization <math>2^2 \cdot 3</math>). In this case we have to count factors of 2 and factors of 3, but it takes ''two'' factors of 2 to make one factor of 12, so we have to divide by two and then compare it with the number of factors of 3 (the smaller of the two results will be the answer). It's not obvious which factor will "run out" first, so it might be necessary to find the number of times ''each'' prime factor in the base appears in <math>n!</math>. The algorithm shown above still works for each individual prime factor, though (provided that "5" is replaced with the appropriate number).
 
Bases other than 10 may be trickier to handle. For example, consider the problem of finding the number of zeroes at the end of <math>n!</math> when expressed in base 12 (with prime factorization <math>2^2 \cdot 3</math>). In this case we have to count factors of 2 and factors of 3, but it takes ''two'' factors of 2 to make one factor of 12, so we have to divide by two and then compare it with the number of factors of 3 (the smaller of the two results will be the answer). It's not obvious which factor will "run out" first, so it might be necessary to find the number of times ''each'' prime factor in the base appears in <math>n!</math>. The algorithm shown above still works for each individual prime factor, though (provided that "5" is replaced with the appropriate number).

Please note that all contributions to PEGWiki are considered to be released under the Attribution 3.0 Unported (see PEGWiki:Copyrights for details). If you do not want your writing to be edited mercilessly and redistributed at will, then do not submit it here.
You are also promising us that you wrote this yourself, or copied it from a public domain or similar free resource. Do not submit copyrighted work without permission!

Cancel | Editing help (opens in new window)