本文實例講述了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
PS:這里再為大家推薦幾款計算工具供大家進一步參考借鑒:
在線分解質因數計算器工具:
http://tools.jb51.net/jisuanqi/factor_calc
在線一元函數(方程)求解計算工具:
http://tools.jb51.net/jisuanqi/equ_jisuanqi
科學計算器在線使用_高級計算器在線計算:
http://tools.jb51.net/jisuanqi/jsqkexue
在線計算器_標準計算器:
http://tools.jb51.net/jisuanqi/jsq
更多關于Python相關內容感興趣的讀者可查看本站專題:《Python數學運算技巧總結》、《Python數據結構與算法教程》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》、《Python入門與進階經典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設計有所幫助。
新聞熱點
疑難解答