t = 0listOfPrimes = [2] for numerator in range(3, 200000, 2): if numerator % 2 != 0: for x in range(0, len(listOfPrimes)): if numerator % listOfPrimes[x] == 0: t += 1 if t == 0: listOfPrimes.append(numerator) else: t = 0 print(len(listOfPrimes), numerator) if len(listOfPrimes) == 10001: break print("10001th prime: ", listOfPrimes[10000])
My intuition says that this problem will take quite some running time to complete, let's see!
I've done some modifications of the code above to make it work theoretically. What annoys me is that it takes so long time to run the algorithm, so I think I'm gonna see how other people solved problem 7 to maybe get some inspiration for a better way. This takes way too long, so I'm going to program the sieve of Eratosthenes algorithm for prime number calculation. On the Euler Project forum, the people who use this algorithm solves problem 7 in (milli)seconds.
It annoys me only a little, but what I did to solve this problem was to find a fast solution for problem 7 from the Project Euler forum and then modify it. The code I chose was posted by onoki_li in May 2017. I then modified it to add all found primes to a list until the next prime was larger than 2,000,000. What bothers me is that I didn't come up with the code myself, but I rationalize it with that this is for Python and not math learning.
from math import sqrt def is_prime(x): for j in range(2, int(sqrt(x)) + 1): if x % j == 0: return False break return True i = 0m = 1listOfPrimes = [] while m < 2000001: m += 1 if is_prime(m): listOfPrimes.append(m) print(sum(listOfPrimes))
/Ludvig
No comments:
Post a Comment