主要因素分解不适用于重复因素的数字
在这段代码中,用户必须输入一个区间,程序必须计算该区间中每个数字的素因数分解。
但是,我无法为具有重复因子的数字(例如 4、8 和 9)打印正确的素因子分解。
我尝试使用 while 循环,但我无法正确使用它,并且我的代码只是不停地运行。
问题要求:求给定区间[a,b]内所有整数的质因数分解。
范围(3,10)的预期输出:
3=3
4=2*2
5=5
6=2*3
7=7
8=2*2*2
9=3*3
10=2*5
我的代码:
a, b = map(int, input().split())
j = [] #list for prime numbers
lst = [] #list for factors for numbers in range(a,b)
# prime numbers
for number in range(2, b+1):
for i in range(2, number):
if number % i == 0:
break
else:
j.append(number)
#factors
for c in range(a, b+1):
lst = []
for i in j:
k = c % i
if k == 0:
lst.append(i)
print(f'{c}=', end='')
print(*lst, sep='*')
我的范围(3,10)的代码输出:
3=3
4=2
5=5
6=2*3
7=7
8=2
9=3
10=2*5
我感谢任何反馈可以得到,谢谢!
In this code, the user has to input an interval, and the program has to calculate the prime factor decomposition for each number in this interval.
However, I am unable to print the correct prime factor decomposition for numbers that have repeated factors, such as 4, 8 and 9.
I tried to use a while loop, but I am unable to use it correctly and my code just runs nonstop.
Problem requirement: Find the prime factorization of all integers in a given interval [a,b].
Expected output for range(3,10):
3=3
4=2*2
5=5
6=2*3
7=7
8=2*2*2
9=3*3
10=2*5
My code:
a, b = map(int, input().split())
j = [] #list for prime numbers
lst = [] #list for factors for numbers in range(a,b)
# prime numbers
for number in range(2, b+1):
for i in range(2, number):
if number % i == 0:
break
else:
j.append(number)
#factors
for c in range(a, b+1):
lst = []
for i in j:
k = c % i
if k == 0:
lst.append(i)
print(f'{c}=', end='')
print(*lst, sep='*')
My Code Output for range (3,10):
3=3
4=2
5=5
6=2*3
7=7
8=2
9=3
10=2*5
I appreciate any feedback I can get, thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
关闭。您必须循环循环直到0。
请注意,我必须移动
print
c
c 到循环的顶部,因为我正在循环中修改c
。我没有注意到直到进行测试。Close. Instead of checking
c % i
just once, you have to loop until that is no longer 0.Note that I had to move the
print
ofc
to the top of the loop, because I'm modifyingc
within the loop. I didn't notice that until I did a test run.