最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
Python实现正整数分解质因数操作示例
时间:2018-08-11 编辑:猪哥 来源:一聚教程网
本文实例讲述了Python实现正整数分解质因数操作。分享给大家供大家参考,具体如下:
遇到一个Python编程练习题目:将一个正整数分解质因数。例如:输入90,打印出90=2*3*3*5。
#!/usr/bin/env python # -*- coding: utf-8 -*- def div_func(n): result = [] while True: for i in xrange(2, int(n**0.5) + 1): if n % i == 0: result.append(i) n /= i break else: result.append(n) break return ' * '.join(map(str, result)) num = raw_input('please enter a number( < 1.0E+18):') try: int_num = int(num) if int_num > 10**18 or int_num < 0: raise ValueError() print div_func(int_num) except ValueError: print 'invalid number'
please enter a number( < 1.0E+18):123124324324134334
2 X 293 X 313 X 362107 X 1853809
自己写的,完全没有参考网上其它人的算法。结果和大家都差不多。
另外还可以用递归方法:
def factor(num): if num == 1: return [] else: for i in range(2, num+1): n, d = divmod(num, i) if d == 0: return [i] + factor(n) for test_num in (299, 1024, 20, 7): print(test_num, '->', ' * '.join(map(str, factor(test_num))))
299 -> 13 * 23
1024 -> 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2
20 -> 2 * 2 * 5
7 -> 7
-
下一个: PHP实现的分解质因数操作示例
相关文章
- Golang ProtoBuf的基本语法详解 10-20
- Python识别MySQL中的冗余索引解析 10-20
- Python+Pygame绘制小球代码展示 10-18
- Python中的数据精度问题介绍 10-18
- Python随机值生成的常用方法介绍 10-18
- python3解压缩.gz文件分析 09-27