checkio (Numbers Factory)

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"


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值