【“炸金花”低配版】Python 拆解因数为235的整数! 小练习系列第二弹

在某人工智能培训班看到这个预热练习,来玩一下~
题目意思说白了就是用户输入一个数,判断其是否只能被2,3,5整除,能就列出被整除的过程,不能就返回None

原题目【吐槽一句真不易读。。】
Simple Number Finding

You are playing a card game with your friends. This game in China named “扎金花”. In this game, the
2, 3, 5 are some simple powerful numbers. Because the combination of 2,3,5 is less than any other combinations but greater than the AAA, which is the king in this game. In today, you want to find if a number is a simple number, in which their factors only include 2, 3 and 5.
So your task is to find out whether a given number is an amazing number.

E.g
Input: 6
Output: (2, 3) Explanation: 6 = 2 x 3
Input: 8
Output: (2, 2, 2) Explanation: 8 = 2 x 2 x 2
Input: 14
Output:None
Explanation: 14 is not amazing since it includes another prime factor 7.

How to check your answer:
If you test 1845281250, your program should give
(2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 5, 5, 5, 5, 5, 5) 10个3,6个5
If you test 3690562500, your program should give (2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 5, 5, 5, 5, 5, 5);
If you test 1230187500, your program should give (2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 5, 5, 5, 5, 5, 5);
If you test 10023750, your program should give None;

思路:把数字格式化后去分别除2,3,5,
除完后判断剩下的部分是不是质数

献上代码:

#列出被2整除的过程
def divide2(ip):
    while ip%2==0:
            ls.append(2)
            ip = ip/2
    return ip
    
#列出被3整除的过程
def divide3(ip):
    while ip%3==0:
        ls.append(3)
        ip = ip/3
    return ip

#列出被3整除的过程
def divide5(ip):
    while ip%5==0:
        ls.append(5)
        ip = ip/5
    return ip

#判断剩余部分是否为质数(1,2,3,5除外),非整数也顺手排除掉了
def prime(n):
    if n == 1 or type(n) != int:
        return False
    else:
        for i in range(2,n):
            if n%i == 0:
                return False
    return True

#把几个函数串一起
def divide(ip):
    ip2 = divide2(ip)
    ip3 = divide3(ip2)
    ip5 = divide5(ip3)
    if prime(int(ip5)):
        print('None')
    else:
        print(ls)

ip = eval(input())
ls = []
#怕出bug,来个try-except       
try:
    divide(ip)
except:
    print('None.')

最后,看到另一位博主的版本,看着真不错:
https://blog.csdn.net/kingroc/article/details/91447690

求大佬指教嘤~
Have fun~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值