熱線電話:13121318867

登錄
首頁精彩閱讀Python實現將一個正整數分解質因數的方法分析
Python實現將一個正整數分解質因數的方法分析
2018-04-21
收藏

Python實現將一個正整數分解質因數的方法分析

本文實例講述了Python實現將一個正整數分解質因數的方法。分享給大家供大家參考,具體如下:
遇到一個python編程聯系題目:將一個正整數分解質因數。例如:輸入90,打印出90=2*3*3*5。
版本一:
開始,沒動腦子就開始寫了,結果如下代碼    
#! /usr/bin/python
# 014.py
import math
number = int(raw_input("Enter a number: "))
while number != 1:
  for i in range(1, number + 1):
    if (number % i) == 0 and i != 1:
      number = number / i
      if number == 1:
        print " %d" %i
      else:
        print " %d*" %i,
      break

結果,輸入9876543210這個十位數的時候,報錯:

Traceback (most recent call last):
  File "./014.py", line 8, in <module>
    for i in range(1, number + 1):
OverflowError: range() result has too many items

版本二:

版本一報錯是因為range有了太多的項,于是想著減少range出的list的項。由于,在判斷一個數n是否是質數的時候,只需從2到n的平方根就行了,所以有了版本二,代碼如下:    
#! /usr/bin/python
# 014_1.py
import math
number = int(raw_input("Enter a number: "))
list = []
def getChildren(num):
  print '*'*30
  isZhishu = True
  for i in range(2, int(math.sqrt(1 + num)) + 1): #多加個1
    if num % i == 0 and i != num :
      list.append(i)
      isZhishu = False
      getChildren(num / i)
      break
  if isZhishu:
    list.append(num)
getChildren(number)
print list

這樣,數字可以增大很多而不至于報錯。但是 ,也是很有限度的,當輸入大數如 123124324324134334 時,會導致內存不足,殺死進程

Traceback (most recent call last):
  File "./014_1.py", line 20, in <module                                            >
    getChildren(number)
  File "./014_1.py", line 11, in getChildren
    for i in range(2, int(math.sqrt(1 +  num)) + 1):
MemoryError

為了追求能對更大的數進行操作,猜想原因可能是遞歸調用時每次都需要建立一個很大的由range()建立的list,于是想避免range的使用,于是有了版本三:

版本三:

代碼    
#! /usr/bin/python
# 014_1.py
import math
number = int(raw_input("Enter a number: "))
list = []
def getChildren(num):
  print '*'*30
  isZhishu = True
  i = 2
  square = int(math.sqrt(num)) + 1
  while i <= square:
    if num % i == 0:
      list.append(i)
      isZhishu = False
      getChildren(num / i)
      i += 1
      break
    i += 1
  if isZhishu:
    list.append(num)
getChildren(number)
print list

同樣對123124324324134334 進行操作,速度很快,得到如下結果

 Enter a number: 123124324324134334
******************************
******************************
******************************
******************************
******************************
[2, 293, 313, 362107, 1853809L]

數據分析咨詢請掃描二維碼

若不方便掃碼,搜微信號:CDAshujufenxi

數據分析師資訊
更多

OK
客服在線
立即咨詢
日韩人妻系列无码专区视频,先锋高清无码,无码免费视欧非,国精产品一区一区三区无码
客服在線
立即咨詢