1

Using Python 3.5.1.

I am trying to build a while loop, which iterates a function until a certain number of prime numbers has been appended into a list. I have previously written a function which takes in a number, evaluates whether or not it is a prime and adds it to a list if it is a prime:

def primelister(n):
    if n < 10:
            return
    else:
            l1=[]
            l2=[]
            ts1=np.arange(1,(n+1),1)
            for i in ts1:
                    if n%i==0:
                            l1.append(i)
                            continue
                    else:
                            continue
            if len(l1) < 3:
                    l2.append(i)
                    print(l2)

This function works ok and seems to give out correct results. I would like to implement the function in to a while loop, where the value of n starts out at 10, and is incremented by 1 at each loop. The loop would go on until a certain number of primes has been reached (i.e. stop when 1000 primes have been listed).

This is what I've tried so far:

    n=10
    l1=[]
    l2=[]

    while numberofprimes < 100:
           ts1=np.arange(1,(n+1),1)
           for i in ts1:
                  if n%i==0:
                         l1.append(i)
                         continue
           if len(l1) < 3:
                  l2.append(i)
           numofprimes=len(l2)
           print("Number of primes so far:", numberofprimes)
           n = n + 1

The loop is obviously broken. The output is just 1 at all times, and the loop seems to be infinite. All help will be appreciated.

Brendan Abel
  • 35,343
  • 14
  • 88
  • 118
Bdrs
  • 143
  • 5
  • You need to reset `l1` each iteration. Move `l1=[]` into the loop. – Aran-Fey Jul 05 '16 at 16:53
  • if you would like to see a really fast and smart implementation of the solution please check out this [link](http://stackoverflow.com/questions/1628949/to-find-first-n-prime-numbers-in-python) – limbo Jul 05 '16 at 16:58

1 Answers1

4

The problem is that you are not resetting l1 after each while loop iteration. Furthermore, you are using numberofprimes as your while loop condition while assigning the number of primes value to numofprimes

import numpy as NP
n=10
l2=[]
numberofprimes = 0
while numberofprimes < 100:
    l1 = []
    ts1=NP.arange(1,(n+1),1)
    for i in ts1:
       if n%i==0:
            l1.append(i)
    if len(l1) < 3:
       l2.append(i)
    numberofprimes=len(l2)
    print("Number of primes so far:", numberofprimes)
    n = n + 1
GWW
  • 43,129
  • 11
  • 115
  • 108