资源限制
内存限制:512.0MB C/C++时间限制:1.0s Java时间限制:3.0s Python时间限制:5.0s
问题描述
求出区间[a,b]中所有整数的质因数分解。
输入格式
输入两个整数a,b。
输出格式
每行输出一个数的分解,形如k=a1*a2*a3...(a1<=a2<=a3...,k也是从小到大的)(具体可看样例)
样例输入
3 10
样例输出
3=3
4=2*2
5=5
6=2*3
7=7
8=2*2*2
9=3*3
10=2*5
提示
先筛出所有素数,然后再分解。
数据规模和约定
2<=a<=b<=10000
import math
a, b = map(int, input().split())
nums = []
for i in range(2, b + 1): # 2~b 之间所有的质数保存到nums中
x = 0
for j in range(2, int(math.sqrt(i) + 1)):
if i % j == 0:
x = 1
break
if x == 0:
nums.append(i)
for i in range(a, b + 1):
# 如果本身就是质数,直接输出
if i in nums:
print(str(i) + "=" + str(i))
else:
# 如果本身不是质数
new_num = i
new_str = []
tmp = 0
while tmp == 0:
for j in nums:
s1 = j # s1,s2是两个因数,s1是质数,s2不一定是
s2 = new_num / j
if s2 % 1 == 0: # 如果s2是整数,则说明s1是i的一个因数
s2 = int(s2)
new_str.append(s1)
if s2 in nums: # 如果s2也是质数,就可以结束了
new_str.append(s2)
tmp = 1
break
elif s2 == 1: # 如果s2是1,也可以结束,但是1不能要
tmp = 1
break
else: # 如果s2不是1,也不是质数,则以s2为目标数,继续往下找
new_num = s2
new_str.sort() # 所有的质因数找到后排个序
ans = [str(i) for i in new_str] # 再将所有的数转换成字符串
print(str(i) + "=" + '*'.join(ans))