1

I see that there are many different ways to generate prime numbers. My code is very long and redundant but I know it can definitely be condensed and made less repetitive with a few changes and I was hoping I could be pointed in the right direction. Essentially I would like to automate the process that is being shown in my code so it can work for any range and all prime numbers.

Here is my code:

def primes():
    multiplesList1 = []
    multiplesList2 = []
    multiplesList3 = []
    multiplesList4 = []
    multiplesList5 = []
    multiplesList6 = []
    multiplesList7 = []
    multiplesList8 = []
    multiplesList9 = []
    for i in range(2,1000):
        if i % 2 != 0 or i == 2:
            multiplesList1.append(i)
    for j in multiplesList1:
        if j % 3 != 0 or j == 3:
            multiplesList2.append(j)
    for x in multiplesList2:
        if x % 5 != 0 or x == 5:
            multiplesList3.append(x)
    for y in multiplesList3:
        if y % 11 != 0 or y == 11:
            multiplesList4.append(y)
    for z in multiplesList4:
        if z % 13 != 0 or z == 13:
            multiplesList5.append(z)
    for a in multiplesList5:
        if a % 17 != 0 or a == 17:
            multiplesList6.append(a)
    for b in multiplesList6:
        if b % 19 != 0 or b == 19:
            multiplesList7.append(b)
    for c in multiplesList7:
        if c % 23 != 0 or c == 23:
            multiplesList8.append(c)
    for d in multiplesList8:
        if d % 29 != 0 or d == 29:
            multiplesList9.append(d)
    return multiplesList9

print(primes())
Chris95
  • 75
  • 1
  • 10

1 Answers1

0

All you need to do is create a second for loop with a range up until the previous number and check each modulus. If 0 is the result then it must not be prime.

if __name__ == "__main__": 
    prime = True
    for i in range(2, 1000):
        for x in range(2, i):
            if i % x == 0:
                prime = False
        if prime:
            print(i)
        prime = True
duncan
  • 1,149
  • 8
  • 14
  • Using a prime number sieve is probably way faster if speed is a concern – Stefan Jun 06 '16 at 18:14
  • @duncan Thank you for this post, it fixed the issue. I was on the verge of this but you helped me get there! – Chris95 Jun 06 '16 at 18:25
  • @duncan I am just wondering what is the purpose of the first line in your code? (if __name__ == "__main__": ) – Chris95 Jun 06 '16 at 18:28
  • No problem. Just a heads up as other people here mentioned if time is an issue this is not the best algorithm. – duncan Jun 06 '16 at 18:29
  • That was cause I double checked my code by adding it to a sort of template I have for testing Python. It is not necessary for this program. Here is a good description http://stackoverflow.com/questions/419163/what-does-if-name-main-do – duncan Jun 06 '16 at 18:32
  • @duncan Ok great, that makes sense. I will take a look at the Sieve of Eratosthenes algorithm to solve the issue of time. – Chris95 Jun 06 '16 at 18:33