python质因数分解
一、质因数分解
n=int(input())
#字典负责存储对应的质数及其指数
d=dict()
while n!=1:
for i in range(2,n+1):
if n%i==0:
if i not in d:
d[i]=1
else:
d[i]+=1
n=n//i
break
二、例题
1.题目:输出所有约数
2.题解
先求出所有的质因数,再用背包思路一步步枚举。
3.代码,详细注释
import math
n=int(input())
#d存储质因数及其指数
d=dict()
#t存储所有的质因数
t=[]
while n!=1:
for i in range(2,n+1):
if n%i==0:
if i not in d:
t.append(i)
d[i]=1
else:
d[i]+=1
n=n//i
break
dp=[[] for i in range(len(t)+1)]
dp[len(t)].append(1)
#枚举所有的质数
for i in range(len(t)-1,-1,-1):
#枚举所有可能的指数 0 ~ d[t[i]]
for j in range(d[t[i]]+1):
#枚举前面质数凑出来的所有可能的不完全约数
for tmp in dp[i+1]:
dp[i].append(tmp*pow(t[i],j))
dp[0].sort()
print(dp[0])