Python script to find Nth prime

Fork me on GitHub

Fork prime repository in GitHub

#7919 - 1000th prime
#541 - 100th prime

## program to find any prime

i=0
pcnt=0

while(1):
    i=i+1
    cnt=0
    for j in range(1,i+1):
        if i%j==0:
            cnt=cnt+1
        else:
            continue

    if cnt==2:
        pcnt=pcnt+1
        if pcnt==1000:
            print pcnt,'th prime is',i
            break

Note: This algorithm is not an efficient one. Change the 1000 to your desired number.

Optimized one is at: https://unreachable2027.wordpress.com/2012/10/02/python-script-to-find-nth-prime-optimized/

Advertisements

3 thoughts on “Python script to find Nth prime

  1. Just a tip: You can use the ‘sourcecode’ tag to display Python code. It will preserve indentation and give you syntax highlighting too.

    You can find out more at Posting Source Code.

    Here’s an example (you have to add an opening bracket to make it work)…

    sourcecode language=”Python”]
    hello = “world”
    [/sourcecode]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s