简体   繁体   English

这段代码中找到素数分解有什么问题

[英]What's the wrong in this code to find prime factorization

I tried to find the prime factorization using this code but the program enter an infinite loop.我试图使用此代码找到素数分解,但程序进入无限循环。 I tried to figure out what makes the program enter this infinite loop but unfortunately I couldn't.我试图弄清楚是什么让程序进入这个无限循环,但不幸的是我不能。 The code is:代码是:

N = int(input())
B = N
L = []
while B != 1:
    for i in range(2,N):
        if N % i ==0:
            L.append(i)
            B = N // i
            break
    else:
        L.append(N)
        B = 1
L.pop()
print(L)

The problem is with break statement, every time when for loop begins and the condition if N % i ==0 is reached forces to start a new for loop and this creates an infinity loop.问题在于break语句,每次当 for 循环开始并且达到条件if N % i ==0强制开始一个新的 for 循环,这会创建一个无限循环。 So what you have to do is removing break所以你要做的就是去除break

N = int(input())
B = N
L = []
while B != 1:
    for i in range(2,N):
        if N % i ==0:
            L.append(i)
            B = N // i
    else:
        L.append(N)
        B = 1
L.pop()
print(L)

Prints out:打印出来:

>>10
>>[2, 5]

EDIT编辑

That's the problem with infinity loop, but won't give you the right answer in some cases eg 20 because its logic is wrong.这就是无限循环的问题,但在某些情况下不会给你正确的答案,例如 20,因为它的逻辑是错误的。 I modified a little bit the code and this is what I have.我修改了一点代码,这就是我所拥有的。

N = int(input())
B = N
L = []
while B != 1:
    for i in range(2,N):
        if N % i ==0:
            L.append(i)
            N = N // i
            break
    else:
        L.append(N)
        B = 1
print(L)

while B != 1: is giving you an infinite loop.而 B != 1: 给你一个无限循环。 You can use a debugger and see that when, for example, N = 9, B never goes to 1 and the script keeps appending 3 to L forever.您可以使用调试器查看,例如,当 N = 9 时,B 永远不会变为 1,并且脚本会永远将 3 附加到 L。

You never increment i.你永远不会增加 i。 The break statement takes you to "while b!= 1". break 语句将您带到“while b!= 1”。 So it appends 2 (or the first factor of N) to L infinitely.所以它无限地将 2(或 N 的第一个因数)附加到 L 上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM