简体   繁体   中英

Efficiency problem or endless for loops - Python

Here is my code for trying to solve Project Euler's third problem in Python:

The prime factors of 13195 are 5, 7, 13 and 29.

What is the largest prime factor of the number 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. It might even be the break in the nested for loop that breaks all of the for loops. 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. The largest prime is 11. but you can get that with a different method.

825 can't be divided by 2, but can by 3. so 825/3=275.

275 can't be divided 3 or 4 but can by 5. 275/5=55.

55 again 5. 55/5=11.

11 can't be divided by any number larger then 5 that's not itself. therefore it is a prime.

This is a hint-ish answer. I can give you the code if you will need it tho.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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