Factorials
The factorial of an integer N, written N!, is the product of all the integers from 1 through N inclusive. The factorial quickly becomes very large: 13! is too large to store in a 32-bit integer on most computers, and 70! is too large for most floating-point variables. Your task is to find the rightmost non-zero digit of n!. For example, 5! = 1 * 2 * 3 * 4 * 5 = 120, so the rightmost non-zero digit of 5! is 2. Likewise, 7! = 1 * 2 * 3 * 4 * 5 * 6 * 7 = 5040, so the rightmost non-zero digit of 7! is 4.
PROGRAM NAME: fact4
INPUT FORMAT
A single positive integer N no larger than 4,220.
SAMPLE INPUT (file fact4.in)
7
OUTPUT FORMAT
A single line containing but a single digit: the right most non-zero digit of N! .
SAMPLE OUTPUT (file fact4.out)
4
思路:就是求余,不过要注意2和5的影响,因为没有2和5的影响乘积的个位必不为0,也就是答案,但要是有2和5的话有可能产生多重进位
如:25*104=2600 进了两位,若直接逐个求余,得到答案将是2,但正确答案是6(随便举个,本题阶乘可能不存在这数据,但可能存在类似的的多重进位)
因此,我选者将2和5的个数用two,five存下来,而相同的2,5个数会产生进位但不影响余数,除去2,5相同的个数后再乘上前面处理的余数(除去2,5的数)求余就是答案
具体代码:
YOUR PROGRAM ('fact4') WORKED FIRST TIME! That's fantastic -- and a rare thing. Please accept these special automated congratulations.
Here are the test data inputs:
Keep up the good work!
Factorials
Russ Cox
The insight for this problem is that 0's at the end of a number come from it being divisible by 10, or equivalently, by 2 and 5. Furthermore, there are always more 2s than 5s in a factorial.
To get the last digit of the factorial, we can run a loop to calculate it modulo 10, as long as we don't include any 2s or 5s in the product. Of course, we want to exclude the same number of 2s and 5s, so that all we're really doing is ignoring 10s. So after the loop, we need to multiply in any extra 2s that didn't have 5s to cancel them out.