Python练习题,分解质因数:将一个整数分解为质因数乘积,如90=233*5
代码一:
k=[]#创建一个列表存放质因数
def su(n):#判断素数的函数
for i in range(2,n):
if (n%i==0):
return 0
else:
continue
return 1
def fen(n):#将数分开
for j in range(n):#控制循环次数
for i in range (2,n):#进行内层循环找出n的因数
if n%i==0:
if su(i):
k.append(i);n=n//i
if su(n):#判断此时的n是否为素数
k.append(n)
break
n=int(input())
fen(n)
s=len(k)
print(n,'=',k[0],end='')
for i in range(1,s):
print('*%d'%k[i],end='')
代码二:
def su(x):#判断一个数是不是质数
for i in range(2, x - 1):
if (x % i == 0):
return 0
else:
continue
return 1
def fen(x):#将输入数字作因数分解,得到质因数和剩余值
for i in range(2, x - 1):
if (x % i == 0):
if (su(i) == 1):
return i, x // i
return 1, x
k = int(input('输入一个数字'))
print( k, '=',end='')
cheng, yu = fen(k)
while (cheng != 1):
print (cheng, '*',end='')
cheng, yu = fen(yu)
print(yu)
代码三:(时间复杂度低)
def isprime(n):
count = 0
for i in range(1, int(n//2 + 1)):
if n % i == 0:
count += 1
if count == 1:
return True
else:
return False
def main():
num = eval(input())
a = int(num)
i = 2
formula = ''
while not isprime(num):
if isprime(i) and num % i == 0:
formula += str(i) + '*'
num /= i
else:
i += 1
formula += str(int(num))
print('{0} = {1}'.format(a, formula))
main()