[英]Finding largest prime factor for a number with python
def prime(x):
for a in range(2, x):
if x%a == 0:
break
else:
return x
num = 0
largest = 0
for i in range(2, 600851475143):
if 600851475143%i == 0:
num = prime(i)
if largest < num:
largest = num
print(largest)
I got the answer but it's not running successfully I'm getting this error: '<' not supported between instances of 'int' and 'NoneType'
Can you please tell me what's wrong with the code?我得到了答案,但它没有成功运行我收到这个错误:
'<' not supported between instances of 'int' and 'NoneType'
你能告诉我代码有什么问题吗? I can't figure it out.我想不通。
When prime
is called with a non-prime, it never executes a return
statement, and thus returns None
.当使用非
prime
调用素数时,它从不执行return
语句,因此返回None
。
prime does return None, if it stops with break. prime 确实返回 None,如果它以 break 停止。
Instead of break, you could use return 0. This won´t run into the same error and will not change largest, since largest>=0.您可以使用 return 0 而不是 break。这不会遇到相同的错误并且不会更改最大,因为最大> = 0。
But I guess this is a very inefficient way to get the largest primefactor.但我想这是获得最大素数的一种非常低效的方法。 It would probably be faster to factorize and then to look for the greatest factor.
分解然后寻找最大的因素可能会更快。
def prime(x) calls break
when if x%a == 0:
is true, but can't return anything. if x%a == 0:
为真,则 def prime(x) 调用break
,但不能返回任何内容。
To solve this issue use:要解决此问题,请使用:
def prime(x):
for a in range(2, x):
if x%a == 0:
break
return x
By the way: Finding Primefactors is more an recursive Problem than an interative.顺便说一句:寻找素数因子更像是一个递归问题,而不是一个交互问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.