我试图找到一个数字的最大素数。当与较小的数字一起使用时,该代码在 IDLE 上正确运行,但当我将较大的数字(如 600851475143)分配给 n 时,似乎根本不会在屏幕上打印任何内容。为什么?
def isPrime(n):
isPrime = True
for i in range(2,n-1):
if n % i == 0:
isPrime = False
return isPrime
largest = 0
n = 600851475143
for i in range(2,n-1):
if isPrime(i) and n % i == 0:
largest = i
n = n / i
continue
print("The largest prime factor is", largest)
顺便说一句,我正在运行 Python 3.3。
==================================================== ==============================
感谢大家!
我将我的原始代码固定如下:
def isPrime(n):
for i in range(2,n-1):
if n % i == 0:
return False
return True
largest = 0
n = 600851475143
for i in range(2,n-1):
if isPrime(i) and n % i == 0:
largest = i
if i == n:
break
n = n / i
print("The largest prime factor is", largest)
就像nakedfanatic 说的,他们的代码运行得更快,我稍微编辑了一下:
largest = 0
n = 600851475143
i = 2
while True:
if n % i == 0:
largest = i
if n == i:
# finished
break
n = n / i
else:
i += 1
print("The largest prime factor is", largest)