number of end 0
by white Shinhuata (http://blog.csdn.net/whiterbear) reprint need to indicate the source, thank you.
(note title from: http://www.pythontip.com/)
Description:
Give you a positive integer list L, such as l=[2,8,3,50], output l the number of all numbers in the end of the product 0,
The result of example L is 2. (Hint: Do not multiply directly, number many, may overflow)
Analysis:
By test instructions can come up with the simplest way, all the elements of the table will be multiplied, the last and 10 to get 0 of the number of the remainder. The hint says it will overflow. However, my test found that Python's long integer is incredibly unlimited, that is, you can multiply the n number and there is no overflow at all. Well, Baidu after the reason is:python operation when the integer data overflow automatically converted to a long integer , Long Integer can handle the range depends on (virtual) memory size.
The corresponding program:
Def zeroCount3 (): Zcount = 0if 0 in L:print 1else:res = 1for i in l:res = res * Iwhile res%10 = 0:zcount + = 1res = res/10p Rint Zcount
Or:
Zcount = 0def Zfun (x, y): Global zcountres = x*ywhile res%10 = 0:zcount + = 1res = Res/10return resdef zeroCount2 (): Reduce ( Zfun, L, 1) Print Zcount
However, this is simple and rude, but it is only suitable for Python, because other languages such as C must overflow. So, we're trying to analyze the data to see if we can find a better way.
We found that the number of end 0 depends on how many of the final 10 are multiplied, and 10 is produced by how many (2,5) pairs depend on it. Because a pair of 2 and 5 can produce a 10. In this way, when the n number in L is multiplied, we can convert each number to the corresponding factor multiplication, and count the number of 2 and 5 pairs in the factor, so that the number of the last 0 can be obtained directly, without having to calculate the entire value of the integer.
For example l=[4,6,32,52,25,79], the product is =2*2 * 2*3 * 2^5 * 2^2*13 * 5^2 * 79, statistically there are 2 (2,5) pairs, so that the final result is 2 0. Tip: The number of 2 in the general factor is much greater than the number of 5 occurrences.
The corresponding program is given here:
Def zeroCount1 (): If 0 in l:print 1else:five_count = 0two_count = 0for L in l:while l%5 = = 0:l = L/5five_count + 1while l% 2 = = 0:l = l/2two_count + 1print min (five_count, Two_count)
Number of end 0