School Assignment? Project Due Tomorrow? Chat LIVE With A Programming Expert!

Welcome to Dream.In.Code
Become an Expert!

Join 307,089 Programmers for FREE! Get instant access to thousands of experts, tutorials, code snippets, and more! There are 2,089 people online right now. Registration is fast and FREE... Join Now!




To find first N prime numbers using Python

 

To find first N prime numbers using Python

trips.dude

26 Oct, 2009 - 09:32 PM
Post #1

New D.I.C Head
*

Joined: 26 Oct, 2009
Posts: 1

Hi All,

I am new to the programming world. I was just writing this code to generate N prime numbers. User should input the value for N which is the total number of prime numbers to print out. I have written this code but it doesnt throw the desired output. Instead it prints the prime numbers till the Nth number.
For eg.: User enters the value of N = 7.
Desired output: 2, 3, 5, 7, 11, 13, 19
Actual output: 2, 3, 5, 7

Kindly advise.

CODE
# To find first 'N' prime numbers

i=1
x = int(input("Enter the number:"))

for k in range (1, (x+1), 1):
    c=0;
    for j in range (1, (i+1), 1):
        a = i%j
        if (a==0):
            c = c+1

    if (c==2):
        print (i)
    else:
        k = k-1

    i=i+1


User is offlineProfile CardPM
+Quote Post


code_m

RE: To Find First N Prime Numbers Using Python

28 Oct, 2009 - 05:50 AM
Post #2

D.I.C Head
**

Joined: 21 Apr, 2009
Posts: 124



Thanked: 8 times
My Contributions
Instead of always just printing your result you should append it to a list (named "results" below):
python
result.append(i)


Then break your loop with a len() test:
python
if len(results) == x:
break


Then print the result outside of your for loops.
python
print " ".join(results)


You might have to fiddle with your loops a little bit, but I'm too tired too be that involved right now tongue.gif

This post has been edited by code_m: 28 Oct, 2009 - 05:52 AM
User is offlineProfile CardPM
+Quote Post

noyesa

RE: To Find First N Prime Numbers Using Python

5 Nov, 2009 - 04:19 PM
Post #3

New D.I.C Head
*

Joined: 1 Apr, 2009
Posts: 26



Thanked: 4 times
My Contributions
What your function appears to be doing is finding all prime numbers that are less than N + 1, which doesn't get you what you want.

To produce n number of primes, you have to monitor the number of primes you've actually output. The following is a more readable approach to this same problem that I wrote for a class. It could be more efficient, but I think it does a good job explaining what's going on:

CODE
# Author: Andrew Noyes

def isPrime(num):
    """Checks num for primality. Returns bool."""

    if num == 2:
        return True
    elif num < 2 or not num % 2:    # even numbers > 2 not prime
        return False

        # factor can be no larger than the square root of num
    for i in range(3, int(num ** .5 + 1), 2):
        if not num % i: return False
    return True



def generatePrimes(n):
    """Returns a list of prime numbers with length n"""
    
    primes = [2,]
    noOfPrimes = 1    # cache length of primes for speed
    testNum = 3 # number to test for primality

    while noOfPrimes < n:
        if isPrime(testNum):
            primes.append(testNum)
            noOfPrimes += 1
        testNum += 2

    return primes


You could also use the len() function to check the length of the primes list, but that is much more expensive than keeping a status variable.

This post has been edited by noyesa: 5 Nov, 2009 - 04:25 PM
User is offlineProfile CardPM
+Quote Post

Fast ReplyReply to this topicStart new topic

Time is now: 11/21/09 11:19AM

Live Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

Tutorials

Programming

Web Development

Reference Sheets

Code Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month