主要因素分解不适用于重复因素的数字

发布于 2025-01-19 13:23:20 字数 941 浏览 1 评论 0原文

在这段代码中,用户必须输入一个区间,程序必须计算该区间中每个数字的素因数分解。

但是,我无法为具有重复因子的数字(例如 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

御弟哥哥 2025-01-26 13:23:20

关闭。您必须循环循环直到0。

#factors
for c in range(a, b+1):
    print(f'{c}=', end='')
    lst = []
    for i in j:
        while i <= c and c % i == 0:
            c //= i
            lst.append(i)

    print(*lst, sep='*')

请注意,我必须移动print c c 到循环的顶部,因为我正在循环中修改c。我没有注意到直到进行测试。

Close. Instead of checking c % i just once, you have to loop until that is no longer 0.

#factors
for c in range(a, b+1):
    print(f'{c}=', end='')
    lst = []
    for i in j:
        while i <= c and c % i == 0:
            c //= i
            lst.append(i)

    print(*lst, sep='*')

Note that I had to move the print of c to the top of the loop, because I'm modifying c within the loop. I didn't notice that until I did a test run.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文