To find first N prime numbers in python

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

    Until we have N primes, take natural numbers one by one, check whether any of the so-far-collected-primes divide it.

    If none does, "yay", we have a new prime...

    that's it.

    >>> def generate_n_primes(N):
    ...     primes  = []
    ...     chkthis = 2
    ...     while len(primes) < N:
    ...         ptest    = [chkthis for i in primes if chkthis%i == 0]
    ...         primes  += [] if ptest else [chkthis]
    ...         chkthis += 1
    ...     return primes
    ...
    >>> print generate_n_primes(15)
    [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
    

提交回复
热议问题