-5

im having trouble writing a program that finds all prime numbers to a n'th number and prints them. Heres what I have so far, if someone could help and explain what im doing wrong, it would be appreciated:

def isPrime (n):
   primeList = [2]
    for i in range (3, n):
        if n%2 == 0 or n%3 == 0:
            break
        else:
            primeList.append(i)
            break
    return (primeList)
Cristik
  • 24,833
  • 18
  • 70
  • 97
  • 1
    formatting is lost in your comment. Please edit your post and add the code from your comment and then remove the comment. – Will May 07 '15 at 21:02
  • 2
    Have you looked at any of the hundreds of other questions on SO regarding finding primes? Scroll down, and look at the right side under **Related**. These questions also popped up when you were initially composing your question, but you apparently ignored them, even though you can find your answers there. – MattDMo May 07 '15 at 21:06
  • The definition of a prime number is contradicted by your code. You add numbers if they are not divisible by 2 and not divisible by 3, but what about numbers like 5, 7, etc? They are also prime and not divisible by 2 and 3. Additionally, there is no reason to break here. Break ends the enclosing loop. – Shashank May 07 '15 at 21:06
  • possible duplicate of [Fastest way to list all primes below N](http://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n) – alexis May 07 '15 at 21:12
  • 4
    Possible duplicate of Every Question Even Slightly Regarding Finding Prime Numbers. – zubergu May 07 '15 at 21:17
  • possible duplicate of [Simple Prime Generator in Python](http://stackoverflow.com/questions/567222/simple-prime-generator-in-python) – pzp May 07 '15 at 21:34

2 Answers2

2

You have to check if your number is divisible for all the primes you added so far instead of check if it is divisible for 2 and 3.

def isPrime (n):
   primeList = [2]
   for i in range (3, n):
       isPrime = True
       for prime in primeList:
           if i % prime == 0:
               isPrime = False
               break
       if isPrime:
           primeList.append(i)
   return primeList
Amaury Medeiros
  • 1,980
  • 3
  • 21
  • 39
1

Yes, you need a sufficient way to determine if a number is prime. As it stands, you only check if the number is divisible by 2 and 3, not 5, or 7 or anything higher. You can check this by looping through the numbers less than your current number:

    for i in range(3, n):
        for j in range(2, i):
            if i % j == 0:
                break
            primeList.append(i) # only runs if loop not broken

    return primeList

I'll leave you to optimize it if you want

Matthew
  • 662
  • 4
  • 11