Sieve of Eratosthenes - Finding Primes Python

前端 未结 17 2300
旧巷少年郎
旧巷少年郎 2020-11-22 04:40

Just to clarify, this is not a homework problem :)

I wanted to find primes for a math application I am building & came across Sieve of Eratosthenes approach.

17条回答
  •  孤街浪徒
    2020-11-22 04:55

    not sure if my code is efficeient, anyone care to comment?

    from math import isqrt
    
    def isPrime(n):
        if n >= 2: # cheating the 2, is 2 even prime?
            for i in range(3, int(n / 2 + 1),2): # dont waste time with even numbers
                if n % i == 0:
                    return False
        return True
    
    def primesTo(n): 
        x = [2] if n >= 2 else [] # cheat the only even prime
        if n >= 2:
            for i in range(3, n + 1,2): # dont waste time with even numbers
                if isPrime(i):
                    x.append(i)  
        return x
    
    def primes2(n): # trying to do this using set methods and the "Sieve of Eratosthenes"
        base = {2} # again cheating the 2
        base.update(set(range(3, n + 1, 2))) # build the base of odd numbers
        for i in range(3, isqrt(n) + 1, 2): # apply the sieve
            base.difference_update(set(range(2 * i, n + 1 , i)))
        return list(base)
    
    print(primesTo(10000)) # 2 different methods for comparison
    print(primes2(10000))
    

提交回复
热议问题