To find first N prime numbers in python

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

提交回复
热议问题