简体   繁体   English

效率问题或无限循环 - Python

[英]Efficiency problem or endless for loops - Python

Here is my code for trying to solve Project Euler's third problem in Python:这是我尝试用 Python 解决Project Euler 的第三个问题的代码:

The prime factors of 13195 are 5, 7, 13 and 29. 13195 的质因数是 5、7、13 和 29。

What is the largest prime factor of the number 600851475143 ?数字 600851475143 的最大质因数是多少?

For some reason, this doesn't give an answer.出于某种原因,这并没有给出答案。 I know that there is a double for loop, which is quite inefficient, but I don't know if the program is still running and trying to compute, or if there is an error.我知道有一个double for 循环,效率很低,但我不知道程序是否仍在运行并尝试计算,或者是否有错误。 It might even be the break in the nested for loop that breaks all of the for loops.甚至可能是嵌套 for 循环中的中断会中断所有 for 循环。 How can I be more efficient with this code?如何使用此代码提高效率? I'm not asking for a direct complete rewrite of my code, but little bits and pieces would be great.我不是要求直接完全重写我的代码,但一点点零碎会很棒。 (And a few hints as well....!) (还有一些提示......!)

def prime_selector(primed_num):
    factors = []
    prime_factors = []
    for x in range(1, primed_num + 1):
        if primed_num % x == 0:
            factors.append(x)
    for i in factors:
        if i > 1:
            for j in range(2, i):
                if i % j == 0:
                    break
            else:
                prime_factors.append(i)
    prime_factors.sort(reverse=True)
    print(prime_factors[0])


prime_selector(600851475143)

I suggest trying a this differently.我建议以不同的方式尝试这个。 For example the number 825. It is 3 5 5*11.例如数字 825。它是 3 5 5*11。 The largest prime is 11. but you can get that with a different method.最大的素数是 11。但是你可以用不同的方法得到它。

825 can't be divided by 2, but can by 3. so 825/3=275. 825不能被2整除,但可以被3整除,所以825/3=275。

275 can't be divided 3 or 4 but can by 5. 275/5=55. 275不能被3或4整除,但可以被5整除。275/5=55。

55 again 5. 55/5=11. 55 又是 5。55/5=11。

11 can't be divided by any number larger then 5 that's not itself. 11 不能除以任何大于 5 的数,这不是它本身。 therefore it is a prime.因此它是素数。

This is a hint-ish answer.这是一个提示性的答案。 I can give you the code if you will need it tho.如果你需要它,我可以给你代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM