python 3.x - Trying to generate primes from 1 - n, but consistently is missing primes 3 and 5.? -
def generate_primes(n): """generate_primes(n) -> list returns list of primes <= n.""" math import sqrt primes = [2] potentialprimes = [] x in range(3, n + 1): potentialprimes.append(x) if x % 2 == 0: potentialprimes.remove(x) currentprime = potentialprimes[0] primes.append(currentprime) while currentprime < sqrt(n): x in potentialprimes: if x % currentprime == 0: potentialprimes.remove(x) currentprime = potentialprimes[0] x in potentialprimes: primes.append(x) print(primes) generate_primes(100)
when try call function, prints this:
[2, 3, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
any idea why? , ways improve code appreciated well.
in while loop set currentprime =5 dont remove potential primes, in next iteration potentialprimes[0] still 5. , 5%5==0 removes potential primes , same 7.
here's code in same style, correctly showing of numbers
def generate_primes(n): math import sqrt primes=[] potentialprimes=range(2,n+1) prime=potentialprimes[0] while prime<sqrt(n): primes.append(prime) potentialprimes.remove(prime) potential in potentialprimes: if potential%prime==0: potentialprimes.remove(potential) prime=potentialprimes[0] potential in potentialprimes: primes.append(potential) number in primes: print number
Comments
Post a Comment