Jim's
Tutorials

Fall 2018
course
site

I created a library function to implement the sieve of eratosthenes and solve a couple prime problems. Here's my implementation:

def sieve(num):
    i = 2
    array = list(range(num))
    while i < math.sqrt(num):   #to get all primes under a number only have to check the sqaure root of that number
        temp = i                #temp to hold starting value of i
        while i < num - 1:
            i = i + temp
            if i < num - 1:     # check if added total is higher than array bounds
                array[i] = 0    # marks all non-primes as 0
        i = temp
        i += 1
    # sets i to the next non-marked number
        while True:
            if array[i] != 0:
                i = array[i]
                break
            else:
                i += 1
    answer = filter(lambda x: x != 0, array)

    return list(answer)

I used it to solve euler problem 3 like this:

from library.sieve import sieve
import math

def euler_3(num):
    '''takes a number as an argument and solves for the greatest prime factor
    of that number'''
    answer = []
    primes = sieve(1000000)
    for i in range(len(primes)):
        if num % primes[i] == 0:
            answer.append(primes[i])      # create an array of prime factors
    return answer[-1]                     # return the greatest prime factor

print(euler_3(600851475143))

and euler 7 like this:

from library.sieve import sieve

#find the 100001'st prime
all_primes = sieve(1000000)

print(all_primes[10001])

Definitely makes life easier.

attachments [paper clip]

  last modified size
TXT euler_3.py Wed Dec 04 2024 08:21 am 539B
TXT euler_7.py Wed Dec 04 2024 08:21 am 195B
TXT sieve.py Wed Dec 04 2024 08:21 am 1.5K
TXT sieve_jims_office.py Wed Dec 04 2024 08:21 am 923B
TXT sieve_test.py Wed Dec 04 2024 08:21 am 204B