-1

I’m new to python and I’m trying to figure out how to make a function where you enter a number and it gives you the number prime.

Example: If I enter 6 it returns 13. Since 13 is the 6th prime.

Preferably no modules except ones in standard library, Thank you

user21302
  • 11
  • 1

2 Answers2

0

This is what you are looking for:

def nth_prime_number(n):
    # initial prime number list
    prime_list = [2]
    # first number to test if prime
    num = 3
    # keep generating primes until we get to the nth one
    while len(prime_list) < n:

        # check if num is divisible by any prime before it
        for p in prime_list:
            # if there is no remainder dividing the number
            # then the number is not a prime
            if num % p == 0:
                # break to stop testing more numbers, we know it's not a prime
                break

        # if it is a prime, then add it to the list
        # after a for loop, else runs if the "break" command has not been given
        else:
            # append to prime list
            prime_list.append(num)

        # same optimization you had, don't check even numbers
        num += 2

    # return the last prime number generated
    return prime_list[-1]

x = nth_prime_number(8)
print(x)
Aditi
  • 820
  • 11
  • 27
0

Try this code ! I am also attach the screenshot of the output .

num=int(input("Enter Position : "))
r =1000
count=0
import sys
for a in range(2,sys.maxsize**10):
    k=0
    for i in range(2,a//2+1):
        if(a%i==0):
            k=k+1

    if(k<=0):
        count=count+1
    if(count==num):
        print("Prime Number at position " , num , " is " , a)  
        break

enter image description here

Usman
  • 1,983
  • 15
  • 28
  • And if I want the prime number 1000, does your code work? – eyllanesc Feb 13 '18 at 05:03
  • yes this was the mistake in my code because I am limit the range to 1000 & prime number at 1000th position is not possible . Now I am updating the code . Thanks @eyllanesc – Usman Feb 13 '18 at 05:09