Quantcast
Channel: Sieve of Eratosthenes - Finding Primes Python - Stack Overflow
Viewing all articles
Browse latest Browse all 28

Answer by lonny for Sieve of Eratosthenes - Finding Primes Python

$
0
0

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

from math import isqrtdef 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 Truedef 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 xdef 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 comparisonprint(primes2(10000))

Viewing all articles
Browse latest Browse all 28

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>