簡體   English   中英

如何找到一個數字的質因數?花了幾個小時試圖弄清楚為什么 if 和 else 會同時執行

[英]how to find the prime factors of a number?spent hours trying to figure out why both the if and else are executed simultaneously

''' #我想打印 num 的素數 #對於最后兩個輸出,如果 else 語句不運行並在此處中斷。因為 if 條件已滿
#如果我在這里打破它如何繼續其他'''

num=147
v=0

val=0
for i in range(2,num):


    if num%i==0:

        for x in range(2,i):

            if i%x==0 :
                print(i)
                print(x)
                print(i/x)
                break    
            else:

                v = i
    else:
        continue


    print('primefacs ',v) 

Python 3.8.1(默認,2020 年 2 月 2 日,08:37:37)

primefacs  3
primefacs  7
21
3
7.0
primefacs  21
49
7
7.0
primefacs  49

else子句應與for循環相關聯,而不是與內部循環部分中的if語句相關聯。

num = 147
v = 0

for i in range(2, num):
    if num % i == 0:
        for x in range(2, i):
            if i % x == 0:
                print(i)
                print(x)
                print(i / x)
                break
        # comes here if we didn't hit the `break` above
        else:
            v = i
    else:
        continue
    print('primefacs ', v)

Output:

primefacs  3
primefacs  7
21
3
7.0
primefacs  7
49
7
7.0
primefacs  7

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM