To find first N prime numbers in python

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

    using a regexp :)

    #!/usr/bin/python
    
    import re, sys
    
    
    def isPrime(n):
        # see http://www.noulakaz.net/weblog/2007/03/18/a-regular-expression-to-check-for-prime-numbers/
        return re.match(r'^1?$|^(11+?)\1+$', '1' * n) == None
    
    
    N = int(sys.argv[1]) # number of primes wanted (from command-line)
    M = 100              # upper-bound of search space
    l = list()           # result list
    
    while len(l) < N:
        l += filter(isPrime, range(M - 100, M)) # append prime element of [M - 100, M] to l
        M += 100                                # increment upper-bound
    
    print l[:N] # print result list limited to N elements
    

提交回复
热议问题