49

Could someone please tell me what I'm doing wrong with this code? It is just printing 'count' anyway. I just want a very simple prime generator (nothing fancy).

import math

def main():
    count = 3
    one = 1
    while one == 1:
        for x in range(2, int(math.sqrt(count) + 1)):
            if count % x == 0: 
                continue
            if count % x != 0:
                print count

        count += 1
Acumenus
  • 41,481
  • 14
  • 116
  • 107
marc lincoln
  • 1,385
  • 4
  • 20
  • 25
  • 2
    Does it not terminate? Not surprising with a "while one == 1:" in it. Does it not produce any output at all? Does it produce non-prime numbers? Is it too slow? Is it not C#? What is the problem? – S.Lott Feb 19 '09 at 21:31
  • If this isn't homework you might want to look into the Sieve of Eratosthenes: http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes – CTT Feb 19 '09 at 21:34
  • I second CTT's comment. It will be just as easy, if not easier to code too. – Himadri Choudhury Feb 19 '09 at 21:36
  • for simple implementations of Sieve of Eratosthenes see: http://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/ – Robert William Hanks Jul 16 '10 at 18:22

26 Answers26

175

There are some problems:

  • Why do you print out count when it didn't divide by x? It doesn't mean it's prime, it means only that this particular x doesn't divide it
  • continue moves to the next loop iteration - but you really want to stop it using break

Here's your code with a few fixes, it prints out only primes:

import math

def main():
    count = 3
    
    while True:
        isprime = True
        
        for x in range(2, int(math.sqrt(count) + 1)):
            if count % x == 0: 
                isprime = False
                break
        
        if isprime:
            print count
        
        count += 1

For much more efficient prime generation, see the Sieve of Eratosthenes, as others have suggested. Here's a nice, optimized implementation with many comments:

# Sieve of Eratosthenes
# Code by David Eppstein, UC Irvine, 28 Feb 2002
# http://code.activestate.com/recipes/117119/

def gen_primes():
    """ Generate an infinite sequence of prime numbers.
    """
    # Maps composites to primes witnessing their compositeness.
    # This is memory efficient, as the sieve is not "run forward"
    # indefinitely, but only as long as required by the current
    # number being tested.
    #
    D = {}
    
    # The running integer that's checked for primeness
    q = 2
    
    while True:
        if q not in D:
            # q is a new prime.
            # Yield it and mark its first multiple that isn't
            # already marked in previous iterations
            # 
            yield q
            D[q * q] = [q]
        else:
            # q is composite. D[q] is the list of primes that
            # divide it. Since we've reached q, we no longer
            # need it in the map, but we'll mark the next 
            # multiples of its witnesses to prepare for larger
            # numbers
            # 
            for p in D[q]:
                D.setdefault(p + q, []).append(p)
            del D[q]
        
        q += 1

Note that it returns a generator.

Acumenus
  • 41,481
  • 14
  • 116
  • 107
Eli Bendersky
  • 231,995
  • 78
  • 333
  • 394
  • 7
    This sieve is very terse. Where did it come from? – SingleNegationElimination Jul 04 '09 at 05:51
  • 1
    That's a really excellent implementation of the Sieve. I've never seen it applied to indefinite ranges before, but it's obvious in retrospect. – Nick Johnson Nov 22 '09 at 16:29
  • 1
    The dictionary operation is time-consuming, if you have enough memory, you had better save all the numbers in the memory instead of use a dictionary to add and remove elements dynamically. – xiao 啸 May 16 '11 at 06:17
  • 2
    @xiao I thought "in" operation was on average constant in time and at worst linear – yati sagade Oct 09 '11 at 08:48
  • @yatisagade, hey, the dictionary implementation in python is based on dynamical set which is not laverage constant. It should be log(n). – xiao 啸 Oct 09 '11 at 09:45
  • 1
    To see this work try it out at http://people.csail.mit.edu/pgbovine/python/tutor.html#mode=edit – fredley Feb 19 '12 at 18:25
  • 7
    See this thread http://code.activestate.com/recipes/117119-sieve-of-eratosthenes/ if you want to see where this code came from, and some faster refinements (4x in my tests) – Nick Craig-Wood May 19 '12 at 08:15
  • 1
    the addition of the values into the dict should really be ***postponed*** until their ***squares*** are seen in the input, as in http://stackoverflow.com/a/10733621/849891 . This brings memory consumption drastically down and improves [orders of growth](http://en.wikipedia.org/wiki/Analysis_of_algorithms#Empirical_orders_of_growth). cf. [test entry](http://ideone.com/WFv4f) and [related discussion](http://stackoverflow.com/a/8871918/849891). – Will Ness Sep 16 '12 at 08:05
  • 6
    so wait how does one use this? – Ferdinando Randisi Nov 24 '17 at 13:36
  • @FerdinandoRandisi: it returns a generator – Eli Bendersky Dec 06 '17 at 23:56
  • This dynamic sieve is very cool. For calibration, making it able to run an infinite generator like this makes it about 3 times slower than a regular static sieve, which pre-populates the sieve up to sqrt(max_prime). – Jonathan Hartley Sep 24 '18 at 03:04
  • 1
    And the 'postponed' version Will Ness links to takes about 0.8 the time of a simple static sieve. – Jonathan Hartley Sep 24 '18 at 03:13
  • 1
    Can someone please give an example of how to use this? Repeatedly saying "It returns a generator" may not be enough to some people new to the language who don't know how to use a generator. Since this method doesn't take any arguments. I'm not able to get any output from this. – gouravkr May 16 '20 at 17:34
  • 1
    how to use: for prime in gen_primes(): – Tony Hansen Jun 02 '20 at 13:01
  • @FerdinandoRandisi one simple way to use this is `print([p for i, p in zip(range(30), gen_primes())])` Another option is `list(itertools.islice(gen_primes, n))`. See also https://stackoverflow.com/a/26186228/507544 – nealmcb Jul 30 '20 at 17:27
15
def is_prime(num):
    """Returns True if the number is prime
    else False."""
    if num == 0 or num == 1:
        return False
    for x in range(2, num):
        if num % x == 0:
            return False
    else:
        return True

>> filter(is_prime, range(1, 20))
  [2, 3, 5, 7, 11, 13, 17, 19]

We will get all the prime numbers upto 20 in a list. I could have used Sieve of Eratosthenes but you said you want something very simple. ;)

aatifh
  • 2,202
  • 3
  • 26
  • 30
  • 2
    1 isn't a prime number. 2 and 3 are prime numbers and are missing. So this already doesn't work for the first three numbers. –  Feb 20 '09 at 09:38
  • 1
    If you go all the way up to the number it will mod to 0 and return false. – humble_coder Mar 26 '11 at 02:25
  • The else is unnecessary. The function will return True if it is a prime without it and it may confuse beginners. –  Feb 07 '17 at 21:35
  • 1
    If you changed `for x in range(2, num)` into `for x in range(2, math.trunc(math.sqrt(num)) + 1)`, then you get the same results, but faster. – Jonathan Hartley Sep 24 '18 at 02:09
14

re is powerful:

import re


def isprime(n):
    return re.compile(r'^1?$|^(11+)\1+$').match('1' * n) is None

print [x for x in range(100) if isprime(x)]

###########Output#############
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
FelixHo
  • 960
  • 9
  • 24
8
def primes(n): # simple sieve of multiples 
   odds = range(3, n+1, 2)
   sieve = set(sum([list(range(q*q, n+1, q+q)) for q in odds], []))
   return [2] + [p for p in odds if p not in sieve]

>>> primes(50)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]

To test if a number is prime:

>>> 541 in primes(541)
True
>>> 543 in primes(543)
False
Acumenus
  • 41,481
  • 14
  • 116
  • 107
dansalmo
  • 10,338
  • 5
  • 50
  • 49
  • 1
    this is not the Sieve of Eratosthenes though, because it finds composites by enumerating the multiples of odds, whereas SoE enumerates the multiples of *primes*. – Will Ness Jun 03 '20 at 09:28
  • so, *almost* the sieve of Eratosthenes. still much better than trial division... – Will Ness Jun 03 '20 at 15:48
8
print [x for x in range(2,100) if not [t for t in range(2,x) if not x%t]]
SergioAraujo
  • 8,735
  • 1
  • 46
  • 37
  • 3
    it is quite simple, but not efficient. on a typical pc, it takes several seconds to work in range(10000) – kmonsoor Dec 23 '13 at 10:15
4

Here's a simple (Python 2.6.2) solution... which is in-line with the OP's original request (now six-months old); and should be a perfectly acceptable solution in any "programming 101" course... Hence this post.

import math

def isPrime(n):
    for i in range(2, int(math.sqrt(n)+1)):
        if n % i == 0: 
            return False;
    return n>1;

print 2
for n in range(3, 50):
    if isPrime(n):
        print n

This simple "brute force" method is "fast enough" for numbers upto about about 16,000 on modern PC's (took about 8 seconds on my 2GHz box).

Obviously, this could be done much more efficiently, by not recalculating the primeness of every even number, or every multiple of 3, 5, 7, etc for every single number... See the Sieve of Eratosthenes (see eliben's implementation above), or even the Sieve of Atkin if you're feeling particularly brave and/or crazy.

Caveat Emptor: I'm a python noob. Please don't take anything I say as gospel.

Kzing
  • 15
  • 6
corlettk
  • 12,040
  • 7
  • 35
  • 50
4

SymPy is a Python library for symbolic mathematics. It provides several functions to generate prime numbers.

isprime(n)              # Test if n is a prime number (True) or not (False).

primerange(a, b)        # Generate a list of all prime numbers in the range [a, b).
randprime(a, b)         # Return a random prime number in the range [a, b).
primepi(n)              # Return the number of prime numbers less than or equal to n.

prime(nth)              # Return the nth prime, with the primes indexed as prime(1) = 2. The nth prime is approximately n*log(n) and can never be larger than 2**n.
prevprime(n, ith=1)     # Return the largest prime smaller than n
nextprime(n)            # Return the ith prime greater than n

sieve.primerange(a, b)  # Generate all prime numbers in the range [a, b), implemented as a dynamically growing sieve of Eratosthenes. 

Here are some examples.

>>> import sympy
>>> 
>>> sympy.isprime(5)
True
>>> list(sympy.primerange(0, 100))
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
>>> sympy.randprime(0, 100)
83
>>> sympy.randprime(0, 100)
41
>>> sympy.prime(3)
5
>>> sympy.prevprime(50)
47
>>> sympy.nextprime(50)
53
>>> list(sympy.sieve.primerange(0, 100))
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
SparkAndShine
  • 14,337
  • 17
  • 76
  • 119
2

Here is a numpy version of Sieve of Eratosthenes having both okay complexity (lower than sorting an array of length n) and vectorization.

import numpy as np 
def generate_primes(n):
    is_prime = np.ones(n+1,dtype=bool)
    is_prime[0:2] = False
    for i in range(int(n**0.5)+1):
        if is_prime[i]:
            is_prime[i*2::i]=False
    return np.where(is_prime)[0]

Timings:

import time    
for i in range(2,10):
    timer =time.time()
    generate_primes(10**i)
    print('n = 10^',i,' time =', round(time.time()-timer,6))

>> n = 10^ 2  time = 5.6e-05
>> n = 10^ 3  time = 6.4e-05
>> n = 10^ 4  time = 0.000114
>> n = 10^ 5  time = 0.000593
>> n = 10^ 6  time = 0.00467
>> n = 10^ 7  time = 0.177758
>> n = 10^ 8  time = 1.701312
>> n = 10^ 9  time = 19.322478
  • 1
    https://en.wikipedia.org/wiki/Analysis_of_algorithms#Empirical_orders_of_growth FTW! – Will Ness Apr 25 '20 at 11:30
  • 1
    BTW - look at the difference between n^6 and n^7. This is due to cash misses, so on a million entries it can hold the array in cash but it can't do it for 10 million. https://en.wikipedia.org/wiki/CPU_cache – Peter Mølgaard Pallesen Apr 27 '20 at 08:58
  • nice. I was dismissing it on account of the first measurement being "too small" but you actually provided an actual explanation! *Empirical orders of growth* is a valuable analysis tool, I can't recommend it enough. (I even posted a Q and an A about it, something about ["painter puzzle"](https://stackoverflow.com/questions/24202687/painter-puzzle-estimation), but it's got only 100 views so far...). maybe if it were more "in vogue", the pandemic response wouldn't be so slow at first, too. – Will Ness Apr 27 '20 at 09:10
2

python 3 (generate prime number)

import math

i = 2
while True:
    for x in range(2, int(math.sqrt(i) + 1)):
        if i%x==0:
            break
    else:
        print(i)
    i += 1
Pmpr
  • 14,501
  • 21
  • 73
  • 91
CPMaurya
  • 144
  • 1
  • 4
1

To my opinion it is always best to take the functional approach,

So I create a function first to find out if the number is prime or not then use it in loop or other place as necessary.

def isprime(n):
      for x in range(2,n):
        if n%x == 0:
            return False
    return True

Then run a simple list comprehension or generator expression to get your list of prime,

[x for x in range(1,100) if isprime(x)]
mmrs151
  • 3,577
  • 2
  • 32
  • 34
1

Another simple example, with a simple optimization of only considering odd numbers. Everything done with lazy streams (python generators).

Usage: primes = list(create_prime_iterator(1, 30))

import math
import itertools

def create_prime_iterator(rfrom, rto):
    """Create iterator of prime numbers in range [rfrom, rto]"""
    prefix = [2] if rfrom < 3 and rto > 1 else [] # include 2 if it is in range separately as it is a "weird" case of even prime
    odd_rfrom = 3 if rfrom < 3 else make_odd(rfrom) # make rfrom an odd number so that  we can skip all even nubers when searching for primes, also skip 1 as a non prime odd number.
    odd_numbers = (num for num in xrange(odd_rfrom, rto + 1, 2))
    prime_generator = (num for num in odd_numbers if not has_odd_divisor(num))
    return itertools.chain(prefix, prime_generator)

def has_odd_divisor(num):
    """Test whether number is evenly divisable by odd divisor."""
    maxDivisor = int(math.sqrt(num))
    for divisor in xrange(3, maxDivisor + 1, 2):
        if num % divisor == 0:
            return True
    return False

def make_odd(number):
    """Make number odd by adding one to it if it was even, otherwise return it unchanged"""
    return number | 1
Sharas
  • 773
  • 7
  • 15
1

This is my implementation. Im sure there is a more efficient way, but seems to work. Basic flag use.

def genPrime():
    num = 1
    prime = False
    while True:
        # Loop through all numbers up to num
        for i in range(2, num+1):
            # Check if num has remainder after the modulo of any previous numbers
            if num % i == 0:
                prime = False
                # Num is only prime if no remainder and i is num
                if i == num:
                    prime = True
                break

        if prime:
            yield num
            num += 1
        else:
            num += 1

prime = genPrime()
for _ in range(100):
    print(next(prime))
Pierre
  • 90
  • 1
  • 6
1

Just studied the topic, look for the examples in the thread and try to make my version:

from collections import defaultdict
# from pprint import pprint

import re


def gen_primes(limit=None):
    """Sieve of Eratosthenes"""
    not_prime = defaultdict(list)
    num = 2
    while limit is None or num <= limit:
        if num in not_prime:
            for prime in not_prime[num]:
                not_prime[prime + num].append(prime)
            del not_prime[num]
        else:  # Prime number
            yield num
            not_prime[num * num] = [num]
        # It's amazing to debug it this way:
        # pprint([num, dict(not_prime)], width=1)
        # input()
        num += 1


def is_prime(num):
    """Check if number is prime based on Sieve of Eratosthenes"""
    return num > 1 and list(gen_primes(limit=num)).pop() == num


def oneliner_is_prime(num):
    """Simple check if number is prime"""
    return num > 1 and not any([num % x == 0 for x in range(2, num)])


def regex_is_prime(num):
    return re.compile(r'^1?$|^(11+)\1+$').match('1' * num) is None


def simple_is_prime(num):
    """Simple check if number is prime
    More efficient than oneliner_is_prime as it breaks the loop
    """
    for x in range(2, num):
        if num % x == 0:
            return False
    return num > 1


def simple_gen_primes(limit=None):
    """Prime number generator based on simple gen"""
    num = 2
    while limit is None or num <= limit:
        if simple_is_prime(num):
            yield num
        num += 1


if __name__ == "__main__":
    less1000primes = list(gen_primes(limit=1000))
    assert less1000primes == list(simple_gen_primes(limit=1000))
    for num in range(1000):
        assert (
            (num in less1000primes)
            == is_prime(num)
            == oneliner_is_prime(num)
            == regex_is_prime(num)
            == simple_is_prime(num)
        )
    print("Primes less than 1000:")
    print(less1000primes)

    from timeit import timeit

    print("\nTimeit:")
    print(
        "gen_primes:",
        timeit(
            "list(gen_primes(limit=1000))",
            setup="from __main__ import gen_primes",
            number=1000,
        ),
    )
    print(
        "simple_gen_primes:",
        timeit(
            "list(simple_gen_primes(limit=1000))",
            setup="from __main__ import simple_gen_primes",
            number=1000,
        ),
    )
    print(
        "is_prime:",
        timeit(
            "[is_prime(num) for num in range(2, 1000)]",
            setup="from __main__ import is_prime",
            number=100,
        ),
    )
    print(
        "oneliner_is_prime:",
        timeit(
            "[oneliner_is_prime(num) for num in range(2, 1000)]",
            setup="from __main__ import oneliner_is_prime",
            number=100,
        ),
    )
    print(
        "regex_is_prime:",
        timeit(
            "[regex_is_prime(num) for num in range(2, 1000)]",
            setup="from __main__ import regex_is_prime",
            number=100,
        ),
    )
    print(
        "simple_is_prime:",
        timeit(
            "[simple_is_prime(num) for num in range(2, 1000)]",
            setup="from __main__ import simple_is_prime",
            number=100,
        ),
    )

The result of running this code show interesting results:

$ python prime_time.py
Primes less than 1000:
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997]

Timeit:
gen_primes: 0.6738066330144648
simple_gen_primes: 4.738092333020177
is_prime: 31.83770858097705
oneliner_is_prime: 3.3708438930043485
regex_is_prime: 8.692703998007346
simple_is_prime: 0.4686249239894096

So I can see that we have right answers for different questions here; for a prime number generator gen_primes looks like the right answer; but for a prime number check, the simple_is_prime function is better suited.

This works, but I am always open to better ways to make is_prime function.

halfer
  • 18,701
  • 13
  • 79
  • 158
rodfersou
  • 874
  • 6
  • 10
  • I have a fastish prime generator ( not as fast as probabilistic isprimes ) but mine is non probabilistic and is quick for that. 0.011779069900512695 to generate those primes. Located here at: https://github.com/oppressionslayer/primalitytest and using a for loop with the lars_next_prime function – oppressionslayer May 29 '20 at 05:39
1

Here is what I have:

def is_prime(num):
    if num < 2:         return False
    elif num < 4:       return True
    elif not num % 2:   return False
    elif num < 9:       return True
    elif not num % 3:   return False
    else:
        for n in range(5, int(math.sqrt(num) + 1), 6):
            if not num % n:
                return False
            elif not num % (n + 2):
                return False

    return True

It's pretty fast for large numbers, as it only checks against already prime numbers for divisors of a number.

Now if you want to generate a list of primes, you can do:

# primes up to 'max'
def primes_max(max):
    yield 2
    for n in range(3, max, 2):
        if is_prime(n):
            yield n

# the first 'count' primes
def primes_count(count):
    counter = 0
    num = 3

    yield 2

    while counter < count:
        if is_prime(num):
            yield num
            counter += 1
        num += 2

using generators here might be desired for efficiency.

And just for reference, instead of saying:

one = 1
while one == 1:
    # do stuff

you can simply say:

while 1:
    #do stuff
fengshaun
  • 1,921
  • 1
  • 14
  • 22
0

Similar to user107745, but using 'all' instead of double negation (a little bit more readable, but I think same performance):

import math
[x for x in xrange(2,10000) if all(x%t for t in xrange(2,int(math.sqrt(x))+1))]

Basically it iterates over the x in range of (2, 100) and picking only those that do not have mod == 0 for all t in range(2,x)

Another way is probably just populating the prime numbers as we go:

primes = set()
def isPrime(x):
  if x in primes:
    return x
  for i in primes:
    if not x % i:
      return None
  else:
    primes.add(x)
    return x

filter(isPrime, range(2,10000))
vtlinh
  • 1,207
  • 2
  • 10
  • 16
0
import time

maxnum=input("You want the prime number of 1 through....")

n=2
prime=[]
start=time.time()

while n<=maxnum:

    d=2.0
    pr=True
    cntr=0

    while d<n**.5:

        if n%d==0:
            pr=False
        else:
            break
        d=d+1

    if cntr==0:

        prime.append(n)
        #print n

    n=n+1

print "Total time:",time.time()-start
Marcus Rickert
  • 3,851
  • 3
  • 21
  • 29
0

If you wanted to find all the primes in a range you could do this:

def is_prime(num):
"""Returns True if the number is prime
else False."""
if num == 0 or num == 1:
    return False
for x in range(2, num):
    if num % x == 0:
        return False
else:
    return True
num = 0
itr = 0
tot = ''
while itr <= 100:
    itr = itr + 1
    num = num + 1
    if is_prime(num) == True:
        print(num)
        tot = tot + ' ' + str(num)
print(tot)

Just add while its <= and your number for the range.
OUTPUT:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101

0

This seems homework-y, so I'll give a hint rather than a detailed explanation. Correct me if I've assumed wrong.

You're doing fine as far as bailing out when you see an even divisor.

But you're printing 'count' as soon as you see even one number that doesn't divide into it. 2, for instance, does not divide evenly into 9. But that doesn't make 9 a prime. You might want to keep going until you're sure no number in the range matches.

(as others have replied, a Sieve is a much more efficient way to go... just trying to help you understand why this specific code isn't doing what you want)

Paul Roub
  • 35,100
  • 27
  • 72
  • 83
0

You need to make sure that all possible divisors don't evenly divide the number you're checking. In this case you'll print the number you're checking any time just one of the possible divisors doesn't evenly divide the number.

Also you don't want to use a continue statement because a continue will just cause it to check the next possible divisor when you've already found out that the number is not a prime.

David Locke
  • 16,816
  • 8
  • 30
  • 53
0

Using generator:

def primes(num):
    if 2 <= num:
        yield 2
    for i in range(3, num + 1, 2):
        if all(i % x != 0 for x in range(3, int(math.sqrt(i) + 1))):
            yield i

Usage:

for i in primes(10):
    print(i)

2, 3, 5, 7

Vlad Bezden
  • 59,971
  • 18
  • 206
  • 157
0

You can create a list of primes using list comprehensions in a fairly elegant manner. Taken from here:

>>> noprimes = [j for i in range(2, 8) for j in range(i*2, 50, i)]
>>> primes = [x for x in range(2, 50) if x not in noprimes]
>>> print primes
>>> [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
randlet
  • 3,238
  • 1
  • 14
  • 21
0

How about this if you want to compute the prime directly:

def oprime(n):
counter = 0
b = 1
if n == 1:
    print 2
while counter < n-1:
    b = b + 2
    for a in range(2,b):
        if b % a == 0:
            break
    else:
        counter = counter + 1
        if counter == n-1:
            print b
-1
def genPrimes():
    primes = []   # primes generated so far
    last = 1      # last number tried
    while True:
        last += 1
        for p in primes:
            if last % p == 0:
                break
        else:
            primes.append(last)
            yield last
Kuldeep K. Rishi
  • 428
  • 3
  • 15
-1

For me, the below solution looks simple and easy to follow.

import math

def is_prime(num):

    if num < 2:
        return False

    for i in range(2, int(math.sqrt(num) + 1)):
        if num % i == 0:
            return False

return True
vxxxi
  • 67
  • 4
  • is_prime(121) == True, but 121 is not prime. – Adam Feb 20 '17 at 22:25
  • @Adam: True, thanks for spotting it. I can't think of any better solution than the ones already proposed by other people in this thread. So I will re-write my solution to match one of those. If I find any new techniques, I will re-visit my solution. – vxxxi Feb 21 '17 at 13:26
-1
def check_prime(x):
    if (x < 2): 
       return 0
    elif (x == 2): 
       return 1
    t = range(x)
    for i in t[2:]:
       if (x % i == 0):
            return 0
    return 1
Jared Burrows
  • 50,718
  • 22
  • 143
  • 180
kn3l
  • 16,471
  • 26
  • 80
  • 116
-1
  • The continue statement looks wrong.

  • You want to start at 2 because 2 is the first prime number.

  • You can write "while True:" to get an infinite loop.

starblue
  • 51,675
  • 14
  • 88
  • 146