方法一:用时最小,不过消耗内存
"""
5、将一个正整数分解质因数。例如:输入90,打印出90=2*3*3*5。
"""
import time
import math
num = int(input("请输入一个正整数:"))
# 计算程序开始时间
start01 = time.time()
# 用来记录用户输入的数字
value = num
# 用来记录计算后得到的值
str01 = ""
i = 2
while True:
if num % 2 == 0:
num = num // 2
str01 += ",2"
elif num % 3 == 0:
num = num // 3
str01 += ",3"
elif num % 5 == 0:
num = num // 5
str01 += ",5"
elif num % 7 == 0:
num = num // 7
str01 += ",7"
else:
"""
在这里还可以在加入一个判断,用来解决不能控制的数
"""
rangeEnd = int(math.sqrt(num)) + 1
while i < rangeEnd:
if num % i == 0:
str02 = str(i)
str01 += "," + str02
num = num // i
else:
i += 1
str04 = "," + str(num)
str01 += str04
break
if str01[0] == ',':
str01 = str01.replace(",", "", 1)
str01 = str01.replace(",", "*", )
else:
str01 = str01.replace(",", "*")
print("%s = %s" % (value, str01))
end01 = time.time()
print("程序运行时间:%f" % (end01 - start01))
方法2:简单,耗时比较长
import math
start02 = time.time()
num = int(input("请输入要分解的数:"))
s = str(num) + "="
i = 2
while i <= num:
if num % i == 0:
if i == num:
s = s + str(i)
else:
s = s + str(i) + "*"
num = num // i
else:
i += 1
print(s)
end02 = time.time()
print("程序运行时间:%f" % (end02-end01))
方法3:
start02 = time.time()
num = int(input("请输入要分解的数:"))
print("%d = " % num, end="")
for i in range(2, int(math.sqrt(num) + 1)):
while num % i == 0:
print("%d * " %i, end="")
num /= i
print("\b\b") # 退格,把最后的一个删除掉。
end02 = time.time()
print("程序运行时间:%f" % (end02-end01))