国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

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

2020-02-16 11:06:04
字體:
來源:轉載
供稿:網友

本文實例講述了Python實現將一個正整數分解質因數的方法。分享給大家供大家參考,具體如下:

遇到一個python編程聯系題目:將一個正整數分解質因數。例如:輸入90,打印出90=2*3*3*5。

版本一:

開始,沒動腦子就開始寫了,結果如下代碼

#! /usr/bin/python# 014.pyimport mathnumber = 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.pyimport mathnumber = 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.pyimport mathnumber = 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 進行操作,速度很快,得到如下結果

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 辰溪县| 博爱县| 汉沽区| 南丰县| 扶绥县| 碌曲县| 临武县| 东山县| 湘潭县| 马边| 泽库县| 高陵县| 榆中县| 临洮县| 同心县| 济南市| 贡觉县| 璧山县| 五大连池市| 西乡县| 奉节县| 巧家县| 乌拉特后旗| 来凤县| 改则县| 万载县| 舒城县| 沾益县| 民勤县| 嘉定区| 凉城县| 专栏| 碌曲县| 衡阳市| 沙雅县| 靖江市| 彝良县| 大理市| 香港 | 西乌| 如东县|