Euler 0010
The Problem:
ListingWe are finding primes again, this time all multiplesthe primes up to 2000000!
We are going to modify the code that was created in Euler Problem 7 to generate up to a number instead of 3up andto 5a underprime 1000.count.Given:Then 3,5,6,9it is a simple matter of summing up all of the primes.
The issue... the last prime generator took 2.4 seconds to generate up to 100,000. So.. It's probably not going to make the Euler 1 minute guarantee if we are allgoing multiplesto of20 3times andthe 5 below 10.number.
Considerations:
WeYeah, couldI iteratetried throughthe everymore multiplebrutish ofgenerator theseand numbersit butdidn't therework... isI'm going to betry overlapa whendifferent theirand multiplespossibly areeven divisiblestranger byapproach.
I ofam them.going Suchto examplesrepresent wouldthe bethreshold 15 or 30. In these casesthat we don't want to add these numbersget to theas totalsan twice.array of numbers. This isdoes whatmean weI needam totrading watch outcomputation for inspace... thebut code.space is cheap.
The Approach:
We
- will
Keepstartiteratingwiththroughanallarray of 2000000 and then cull out 0 and 1.
Then we start at 2, ignore it, and mark everything that is a multiple of 2.
Then we go to 3, ignore it, and mark everything that is a multiple of 3.
We will keep going until there are no more numbers to check.Basically, it's the
multiplessieve of3Eratosthenes.and 5Add each number to a set, or a list with a not in conditionalSum the set or list
The Code:
target_underprime_threshold = 10002000000
multiplesnumber_list = [3,5]list(range(2, foundprime_threshold+1)) #initiating the sieve. Lot's of space here on startup being used
prime_list = []
#gocurrent = 0
total_iteration = 0
while current < len(number_list): #while we haven't iterated through each of our multiples
for multiple in multiples:
#set the runningwhole totalsieve equalyet
toif thenumber_list[current] first multiple
running_total != multiple-1: #keep incrementing until we go over the target, then go to#find the next multiplenumber whilethat running_totalisn't <marked
target_under:prime = number_list[current]
prime_list += [prime] #add the running totalit to theour listprime iflist, because it is notprime.
alreadyincrement in= it.current if+ running_totalprime
notwhile inincrement found:< foundlen(number_list): #and go through the rest of the sieve marking numbers with it
number_list[increment] = -1
increment += [running_total]prime
running_totaltotal_iteration += multiple1
current += 1
print(len(prime_list)) #look at the length of the prime list, this is the number of primes under prime_threshold
print(total_iteration) #the amount of iterations that we made, much better than recalculating primes for each number
print(sum(prime_list)) #the answer