題目是:寫出一個function 叫 Primefactor(n),做質因數分解將參數n傳入之後,回傳一個list儲存n的質因數與該質因數出現次數,例如傳入120時120=22235,回傳[(2,3),(3,1),(5,1)]出來
以下是我寫的,但是我就是不知道怎麼做最後一步回傳出質因數的次數
def prime_factoring(n):
divisor = 2
factors = []
while divisor * divisor <= n:
if n % divisor:
divisor += 1
else:
n //= divisor
factors.append(divisor)
if n > 1:
factors.append(n)
return factors
aNumber = (int)(input("Enter a number:"));
print(prime_factoring(aNumber))
import math
def prime_factoring(n):
factors = list()
for d in range(2, math.floor(n/2)+1):
td = prime_factoring(d)
# 質數 = 除了1跟自己之外,沒有任一數能整除
if len(list(filter(lambda x : x[1]>0, td)))==0:
factors.append([d, 1 if n % d == 0 else 0])
return factors
aNumber = (int)(input("Enter a number:"))
print(prime_factoring(aNumber))
Enter a number:100
[[2, 1], [3, 0], [5, 1], [7, 0], [11, 0], [13, 0], [17, 0], [19, 0], [23, 0], [29, 0], [31, 0], [37, 0], [41, 0], [43, 0], [47, 0]]
土法煉鋼提供您參考:
def prime_factoring(n):
divisor = 2
factors = []
while divisor * divisor <= n:
if n % divisor:
divisor += 1
else:
n //= divisor
factors.append(divisor)
if n > 1:
factors.append(n)
#利用set不重覆的特性取得質數種類
tmp_set=set(ii for ii in factors)
final=[]
for jj in tmp_set:
#利用list.count()函式取得加總結果
final.append((jj,factors.count(jj)))
return final
aNumber = (int)(input("Enter a number:"))
print(prime_factoring(aNumber))
OUTPUT:
Enter a number:120
[(2, 3), (3, 1), (5, 1)]
from collections import OrderedDict
def prime_factoring(n):
divisor = 2
factors = []
while divisor * divisor <= n:
if n % divisor:
divisor += 1
else:
n //= divisor
factors.append(divisor)
if n > 1:
factors.append(n)
return factors
def group_list(lst):
res = [(el, lst.count(el)) for el in lst]
return list(OrderedDict(res).items())
aNumber = (int)(input("Enter a number:"));
print(group_list(prime_factoring(aNumber)))
def prime_factoring(num):
if num < 2:
return None
def checkPrime(n):
for i in range(2, n):
if n % i == 0:
return False
return True
def groupByFactor(n, pri):
counter = 0
while n % pri == 0:
counter += 1
n = n / pri
return (pri, counter)
primeFactors = (i for i in range(2, int(num*0.5)+1) if checkPrime(i) and num % i == 0)
return [groupByFactor(num, i) for i in primeFactors]