leetcode:Binary Search 793. Preimage Size of Factorial Zeroes Function

Let f(x) be the number of zeroes at the end of x!. (Recall that x! = 1 * 2 * 3 * ... * x, and by convention, 0! = 1.)

For example, f(3) = 0 because 3! = 6 has no zeroes at the end, while f(11) = 2 because 11! = 39916800 has 2 zeroes at the end. Given K, find how many non-negative integers x have the property that f(x) = K.

Example 1:
Input: K = 0
Output: 5
Explanation: 0!, 1!, 2!, 3!, and 4! end with K = 0 zeroes.

Example 2:
Input: K = 5
Output: 0
Explanation: There is no x such that x! ends in K = 5 zeroes.

Note:

  • K will be an integer in the range [0, 10^9].

一个数的阶乘末尾的0的个数等于阶乘中“所有项质因数分解后,数字5的个数之和”,例如5、10、15、20含有1个5,25含有两个5,125含有3个5。因此25!末尾有6个0。原因在于这些数质因数分解后,数字2的个数总多于数字5的个数。2和5刚好可以凑成一个10。

我们可以确认两点:

  1.   一旦有一个数阶乘的末尾有K个0,那么我们可以在这个数的周围找到5个这样的数。比如25,26,27,28,29。
  2.  无论怎样,满足此特性的数都不超过5个。否则其中至少有一个数的质因数分解中数字5的个数会与其他数不同。比如24,25,26,27,28,29

因此我们可以利用二分查找,来找到任何一个具有此特性这个数。

首先,我们要确定二分查找的上下界,首先可确定下界为0,而上界我们用(K+1)*5来确定,原因这个数的阶乘项质因数分解后,其中数字5的个数之和一定大于等于K+1。随后开始查找。

class Solution:   			
	def preimageSizeFZF(self, K):
		high = (K+1)*5  	
		low = 0				
		while low<=high:
			mid = (low+high)//2
			if self.zero(mid)<K:
				low = mid+1
			elif self.zero(mid)>K:
				high = mid-1
			elif self.zero(mid)==K:
				return 5
		return 0	
		
	def zero(self,i):	
		count = 0
		while i>0:
			count += i//5
			i = i//5
		return count	

猜你喜欢

转载自blog.csdn.net/w16337231/article/details/80161204