查找数字60085147514的最大素数(项目Euler#3)

问题描述 投票:0回答:1

我必须找到数字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))
python primes factors
1个回答
0
投票

已修复

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))

两个问题

  1. 用于检查从2开始的素数,因为1将除以所有数
  2. 在将x设置为false后中断,否则将再次将其设置为true,并继续将所有内容追加到列表中
© www.soinside.com 2019 - 2024. All rights reserved.