To find first N prime numbers in python

前端 未结 29 1910
醉梦人生
醉梦人生 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:35
    def isPrime(y):
      i=2
      while i < y:
        if y%i == 0 :
          return 0
          exit()
        i=i+1
      return 1
    
    x= raw_input('Enter the position 1st,2nd,..nth prime number you are looking for?: ')
    z=int(x)
    # for l in range(2,z)
    count = 1
    n = 2
    while count <= z:
      if isPrime(n) == 1:
        if count == z:
          print n
        count +=1
      n=n+1
    
    0 讨论(0)
  • 2020-11-28 07:38
    n=int(input("Enter the number:: "))
    
    for i in range(2,n):
        p=i
        k=0
        for j in range(2,p-1):
            if(p%j==0):
                k=k+1
        if(k==0):
            print(p)
    
    0 讨论(0)
  • 2020-11-28 07:38
    count = -1
    n = int(raw_input("how many primes you want starting from 2 "))
    primes=[[]]*n
    for p in range(2, n**2):
        for i in range(2, p):
            if p % i == 0:
                break
        else:
            count +=1
            primes[count]= p
            if count == n-1:
                break
    
    print (primes)
    print 'Done'
    
    0 讨论(0)
  • 2020-11-28 07:39

    What you want is something like this:

    x = int(input("Enter the number:"))
    count = 0
    num = 2
    while count < x:
         if isnumprime(x):
            print(x)
            count += 1
         num += 1
    

    I'll leave it up to you to implement isnumprime() ;) Hint: You only need to test division with all previously found prime numbers.

    0 讨论(0)
  • 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]
    
    0 讨论(0)
  • 2020-11-28 07:39

    Try using while loop to check the count, that is easy. Find the code snippet below :

    i=1
    count = 0;
    x = int(input("Enter the number:\n"))
    while (count < x):
    c=0
    for j in range (1, (i+1), 1):
        a = i%j
        if (a==0):
            c = c+1
    
    if (c==2):
          print (i)
          count = count+1
    i=i+1
    
    0 讨论(0)
提交回复
热议问题