[英]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.