To find first N prime numbers in python

前端 未结 29 1912
醉梦人生
醉梦人生 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:47

    Here's a simple recursive version:

    import datetime
    import math
    
    def is_prime(n, div=2):
        if div> int(math.sqrt(n)): return True
        if n% div == 0:
            return False
        else:
            div+=1
            return is_prime(n,div)
    
    
    now = datetime.datetime.now()
    
    until = raw_input("How many prime numbers my lord desires??? ")
    until = int(until)
    
    primelist=[]
    i=1;
    while len(primelist)<until:
        if is_prime(i):
            primelist.insert(0,i)
            i+=1
        else: i+=1
    
    
    
    print "++++++++++++++++++++"
    print primelist
    finish = datetime.datetime.now()
    print "It took your computer", finish - now , "secs to calculate it"
    

    Here's a version using a recursive function with memory!:

    import datetime
    import math
    
    def is_prime(n, div=2):
        global primelist
        if div> int(math.sqrt(n)): return True
        if div < primelist[0]:
            div = primelist[0]
            for x in primelist:
                if x ==0 or x==1: continue
                if n % x == 0:
                    return False
        if n% div == 0:
            return False
        else:
            div+=1
            return is_prime(n,div)
    
    
    now = datetime.datetime.now()
    print 'time and date:',now
    
    until = raw_input("How many prime numbers my lord desires??? ")
    until = int(until)
    
    primelist=[]
    i=1;
    while len(primelist)<until:
        if is_prime(i):
            primelist.insert(0,i)
            i+=1
        else: i+=1
    
    
    
    print "Here you go!"
    print primelist
    
    finish = datetime.datetime.now()
    print "It took your computer", finish - now , " to calculate it"
    

    Hope it helps :)

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

    This code is very confused, and I can't figure out exactly what you were thinking when you wrote it or what you were attempting to accomplish. The first thing I would suggest when trying to figure out how to code is to start by making your variable names extremely descriptive. This will help you get the ideas of what you're doing straight in your head, and it will also help anyone who's trying to help you show you how to get your ideas straight.

    That being said, here is a sample program that accomplishes something close to the goal:

    primewanted = int(input("This program will give you the nth prime.\nPlease enter n:"))
    if primewanted <= 0:
        print "n must be >= 1"
    else:
        lastprime = 2 # 2 is the very first prime number
        primesfound = 1  # Since 2 is the very first prime, we've found 1 prime
        possibleprime = lastprime + 1 # Start search for new primes right after
        while primesfound < primewanted:
            # Start at 2.  Things divisible by 1 might still be prime
            testdivisor = 2
            # Something is still possibly prime if it divided with a remainder.
            still_possibly_prime = ((possibleprime % testdivisor) != 0)
            # (testdivisor + 1) because we never want to divide a number by itself.
            while still_possibly_prime and ((testdivisor + 1) < possibleprime):
                testdivisor = testdivisor + 1
                still_possibly_prime = ((possibleprime % testdivisor) != 0)
            # If after all that looping the prime is still possibly prime,
            # then it is prime.
            if still_possibly_prime:
                lastprime = possibleprime
                primesfound = primesfound + 1
            # Go on ahead to see if the next number is prime
            possibleprime = possibleprime + 1
        print "This nth prime is:", lastprime
    

    This bit of code:

            testdivisor = 2
            # Something is still possibly prime if it divided with a remainder.
            still_possibly_prime = ((possibleprime % testdivisor) != 0)
            # (testdivisor + 1) because we never want to divide a number by itself.
            while still_possibly_prime and ((testdivisor + 1) < possibleprime):
                testdivisor = testdivisor + 1
                still_possibly_prime = ((possibleprime % testdivisor) != 0)
    

    could possibly be replaced by the somewhat slow, but possibly more understandable:

            # Assume the number is prime until we prove otherwise
            still_possibly_prime = True
            # Start at 2.  Things divisible by 1 might still be prime
            for testdivisor in xrange(2, possibleprime, 1):
                # Something is still possibly prime if it divided with a
                # remainder.  And if it is ever found to be not prime, it's not
                # prime, so never check again.
                if still_possibly_prime:
                    still_possibly_prime = ((possibleprime % testdivisor) != 0)
    
    0 讨论(0)
  • 2020-11-28 07:49

    Here's what I eventually came up with to print the first n primes:

    numprimes = raw_input('How many primes to print?  ')
    count = 0
    potentialprime = 2
    
    def primetest(potentialprime):
        divisor = 2
        while divisor <= potentialprime:
            if potentialprime == 2:
                return True
            elif potentialprime % divisor == 0:
                return False
                break
            while potentialprime % divisor != 0:
                if potentialprime - divisor > 1:
                    divisor += 1
                else:
                    return True
    
    while count < int(numprimes):
        if primetest(potentialprime) == True:
            print 'Prime #' + str(count + 1), 'is', potentialprime
            count += 1
            potentialprime += 1
        else:
            potentialprime += 1
    
    0 讨论(0)
  • 2020-11-28 07:51

    I am not familiar with Python so I am writing the C counter part(too lazy to write pseudo code.. :P) To find the first n prime numbers.. // prints all the primes.. not bothering to make an array and return it etc..

    void find_first_n_primes(int n){
       int count = 0;
       for(int i=2;count<=n;i++){
         factFlag == 0; //flag for factor count... 
         for(int k=2;k<sqrt(n)+1;k++){
           if(i%k == 0) // factor found..
            factFlag++;
         }
          if(factFlag==0)// no factors found hence prime..
            {
             Print(i);   // prime displayed..
             count++;
            }
       }
    }
    
    0 讨论(0)
  • 2020-11-28 07:52
    #!/usr/bin/python3
    import sys
    
    primary_numbers = [1, 2]
    
    
    def is_prime(i):
        for pn in enumerate(primary_numbers[2:]):
            if i % pn[1] == 0:
                return False
    
        return True
    
    def main(position):
        i = 3
        while len(primary_numbers) < int(position):
            print(i)
            res = is_prime(i)
            if res:
                primary_numbers.append(i)
            i += 2
    
    
    if __name__ == '__main__':
        position = sys.argv[1]
        main(position)
        print(primary_numbers)
    
    0 讨论(0)
  • 2020-11-28 07:52

    This might help:

    def in_prime(n):
        p=True
        i=2
        if i**2<=n:
            if n%i==0:
                p=False
                break
        if (p):
            return n
    
    0 讨论(0)
提交回复
热议问题