1.最大公约数
最大公因子,指两个或多个整数共有约数中最大的一个。如(12,16)的公约数有1,2,4,最大的为4。
| def gcd(x, y): |
| (x, y) = (y, x) if x > y else (x, y) |
| for factor in range(x, 0, -1): |
| if x % factor == 0 and y % factor == 0: |
| return factor |
(x, y) = (y, x) if x > y else (x, y)
等效于
| if x > y: |
| (x, y) = (y, x) |
| else: |
| (x, y) = (x, y) |
2.最小公倍数
两个或多个整数有最小的倍数。如(30,45)的最小公倍数为90。
| def lcm(x, y): |
| return x * y // gcd(x, y) |
3.回文数
正反都一样的数,如121、484、676。
把数反转,再和原来的比较。
| def is_palindrome(num): |
| temp = num |
| total = 0 |
| while temp > 0: |
| total = total * 10 + temp % 10 |
| temp //= 10 |
| return total == num |
| |
4.素数
除了1和它本身之外不再有其他因子,如5,7,11,13。
num**
5表示num的0.5次方,即对num开平方根
| def is_prime(num): |
| for factor in range(2, int(num ** 0.5) + 1): |
| if num % factor == 0: |
| return False |
| return True if num != 1 else False |
5.回文数素数
| if __name__ == '__main__': |
| num = int(input('请输入正整数:')) |
| if is_palindrome(num) and is_prime(num): |
| print('%d是回文素数' % num) |
| else: |
| print("啥也不是") |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本