简体   繁体   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

''' #i want to print the prime factors of num #for the last two outputs should the else statement not run and break here.as the if condition is full filled ''' #我想打印 num 的素数 #对于最后两个输出,如果 else 语句不运行并在此处中断。因为 if 条件已满
#if i break here how does it continue to else''' #如果我在这里打破它如何继续其他'''

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 (default, Feb 2 2020, 08:37:37) 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

The else clause should be associated with the for -loop, not the if -statement in your inner loop part. 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: 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.

相关问题 试图找出一个数字是否存在,总共有 X 个正因子,其中有 K 个不同的素因子 - Trying to find if a number exists with total of X positive factors out of which there are K distinct prime factors 如何使用python查找数字的素因 - How to find the prime factors of a number with python 在给定素数分解的情况下,如何找到数的因子? - How to find the factors of a number given the prime factorization? 这里,对于一个非素数,执行了内循环的break语句,但不执行外循环的else语句,为什么? - here, for a non prime number, the break statement in the inner loop is executed but the else statement of the outer loop is not executed, why? 我有一个数字的素因子的Python列表。 我如何(pythonically)找到所有因素? - I have a Python list of the prime factors of a number. How do I (pythonically) find all the factors? 试图找到素数的python代码。 代码计数不是素数。 找不到原因 - python code trying to find prime number. Code is counting not prime number. Can't find why 我怎样才能找到素因数 - How can i find Prime factors 如何使用python查找素数 - how to find Prime factors using python 寻找数字的素因子 - Finding prime factors of a number 试图找到下一个质数 - Trying to find the next prime number
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM