我必须找到数字600851475143中最大的素数。答案是6857,但我不断收到486847。代码中的错误是什么?
def f(n):
factors = []
for i in range(1, int(math.sqrt(n))+1): #check if it is a factor
if n%i == 0:
x = True
for j in range(1, int(math.sqrt(i))+1): #check if factor is prime
if i%j == 0:
x = False
x = True
if x:
factors.append(i)
return max(factors)
print(f(600851475143))
已修复
import math
def f(n):
factors = []
for i in range(1, int(math.sqrt(n))+1): #check if it is a factor
if n%i == 0:
x = True
for j in range(2, int(math.sqrt(i))+1): #check if factor is prime
if i%j == 0:
x = False
break
x = True
if x:
factors.append(i)
return max(factors)
print(f(600851475143))
两个问题
x
设置为false后中断,否则将再次将其设置为true,并继续将所有内容追加到列表中