To find first N prime numbers in python

前端 未结 29 1911
醉梦人生
醉梦人生 2020-11-28 06:56

I am new to the programming world. I was just writing this code in python to generate N prime numbers. User should input the value for N which is the total number of prime n

相关标签:
29条回答
  • 2020-11-28 07:39

    Try this:

    primeList = []
    for num in range(2,10000):
        if all(num%i!=0 for i in range(2,num)):
            primeList.append(num)
    x = int(raw_input("Enter n: "))
    for i in range(x):
        print primeList[i]
    
    0 讨论(0)
  • 2020-11-28 07:41

    Whilst playing with prime numbers in Python V3 I noticed that the smallest number by which a composite(non-prime) number is divisible is itself always a prime that is less than the square root of the number under test.

    Below is my implementation of that finding to calculate the first N prime numbers.

    first 1,000 primes in 0.028S | first 10,000 primes in 0.6S | first 100,000 primes in 14.3S

    The snippet below also indicates how long the generation took and prints out the primes in a nice table format.

    import time
    import math
    
    def first_n_Primes(n):
        number_under_test = 4
        primes = [2,3]
        while len(primes) < n:
            check = False
            for prime in primes:
                if prime > math.sqrt(number_under_test) : break
                if number_under_test % prime == 0:
                    check = True
                    break
            if not check:
                for counter in range(primes[len(primes)-1],number_under_test-1,2):
                    if number_under_test % counter == 0:
                        check = True
                        break
            if not check:
                primes.append(number_under_test)
            number_under_test+=1
        return primes
    
    start_time = time.time()
    data = first_n_Primes(1000)
    end_time = time.time()
    
    i = 1
    while i < len(data)+1:
        print('{0: <9}'.format(str(data[i-1])), end="")
        if i%10 == 0: print("")
        i+=1
    
    print("\nFirst %d primes took %s seconds ---" % (len(data),end_time - start_time))
    
    0 讨论(0)
  • 2020-11-28 07:41
    max = input("enter the maximum limit to check prime number");
    if max>1 :
        for i in range (2,max):
            prime=0;
            for j in range (2,i):
                if(i%j==0):
                    prime=1;
                    break
            if(prime==0 and i!=0):
                print(i,"is prime number");
    else:
        print("prime no start from 2");
    
    0 讨论(0)
  • 2020-11-28 07:44

    Super quick sieve implementation by David Eppstein - takes 0.146s for the first 1000 primes on my PC:

    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
    
    primes = gen_primes()
    
    
    x = set()
    y = 0
    a = gen_primes()
    while y < 10000:
      x |= set([a.next()])
      y+=1
    
    print "x contains {:,d} primes".format(len(x))
    print "largest is {:,d}".format(sorted(x)[-1])
    
    0 讨论(0)
  • 2020-11-28 07:44

    You don't need to declare that many variables, see the below code is simple and easy to understand.

    for num in range(1,50):     
       for i in range(2,num):    
          if num%i == 0:                  
             break 
       else:                 
          print(num,'is a prime')
    

    First 50 prime numbers output

    0 讨论(0)
  • 2020-11-28 07:46

    This might help:

    import sys
    from time import time
    def prime(N):
        M=100
        l=[]
        while len(l) < N:
            for i in range(M-100,M):    
                num = filter(lambda y :i % y == 0,(y for y in range(2 ,(i/2)))) 
                if not num and i not in [0,1,4]:
                    l.append(i)
            M +=100
        return l[:N]
    
    
    def dotime(func, n):
        print func.__name__
        start = time()
        print sorted(list(func(n))),len(list(func(n)))
        print 'Time in seconds: ' + str(time() - start)
    
    
    if __name__ == "__main__":
        dotime(prime, int(sys.argv[1]))
    
    0 讨论(0)
提交回复
热议问题