You are given a two or more digits number N. For this mission, you should find the smallest positive number of X, such that the product of its digits is equal to N. If X does not exist, then return 0.
Let's examine the example. N = 20. We can factorize this number as 2*10, but 10 is not a digit. Also we can factorize it as 4*5 or 2*2*5. The smallest number for 2*2*5 is 225, for 4*5 -- 45. So we select 45.
Hints: Remember prime numbers (numbers divisible by only one) and be careful with endless loops.
Input: A number N, an integer.
Output: The number X, an integer.
Example:
|
1
2
3
4
|
checkio(20) == 45
checkio(21) == 37
checkio(17) == 0
checkio(33) == 0
|
How it is used: This task will teach you how to work with numbers in code. You can factorize numbers and reconstruct them into new numbers. Of course you can solve this problem with brute force, but is that the best way? Numbers are the foundation of mathematics and programming.
Precondition: 9 < N < 105.
解法就是让因数尽量大(可以简单证明,先做质因数分解,然后再考虑2、3的组合),所以从9开始做除法,直到2。最后若被除数不是1,说明原来的数是大于10的质数,答案为0。
def checkio(number):
ans = ''
digit = 9
while digit > 1:
if number%digit != 0:
digit -= 1
else:
ans = str(digit) + ans
number /= digit
if number == 1:
return int(ans)
else:
return 0
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
assert checkio(20) == 45, "1st example"
assert checkio(21) == 37, "2nd example"
assert checkio(17) == 0, "3rd example"
assert checkio(33) == 0, "4th example"
assert checkio(3125) == 55555, "5th example"
assert checkio(9973) == 0, "6th example"
本文介绍了一种算法,用于找到给定数字N的最小正数X,使得X的各位数字相乘等于N。通过逐步分解并重组数字来解决这个问题,避免了穷举法的效率低下。
688

被折叠的 条评论
为什么被折叠?



