3

I've written a function, isprime(n), that returns True if a number is prime and false if not. I am able to loop the function a defined number of times; but I can't figure out how to iterate until it finds x number of primes. I feel as though I have a decent understanding of For and While loops, but am confused as to how one integrates boolean return values into loops. Here is my current code and error:

Error result:

input:100
Traceback (most recent call last):
File "euler7.py", line 25, in <module>
primeList += 1
TypeError: 'int' object is not iterable

And the code:

def isprime(n):
    x = 2
    while x < sqrt(n):
        if n % x == 0:
            return False
        else:
            x += 1
    return True

userinput = int(raw_input('input:'))

primeList = []
primesFound = 0

while primesFound != userinput:
    i = 2
    if isprime(i):
        primeList.append(i)
        primeList += 1
        i += 1
    else:
        i += 1

EDIT (including the updated and functioning code):

from math import sqrt
def isprime(n):
    x = 2
    while x < (sqrt(n) + 1):
        if n % x == 0:
            return False
        else:
            x += 1
    return True

userinput = int(raw_input('input:'))
primeList = []
primeList.append(2)

i = 2
while len(primeList) != userinput:
    if isprime(i):
        primeList.append(i)
        i += 1
    else:
        i += 1

print 'result:', primeList[-1]
surfearth
  • 2,617
  • 4
  • 21
  • 30

5 Answers5

2

This line:

primeList += 1

Should be:

primesFound += 1
Blender
  • 257,973
  • 46
  • 399
  • 459
2

You cannot add and int to a python list. You should do primesFound += 1 to achieve your desired result.

Plus, your isprime function is wrong. It will return True for 9. You should do while x < sqrt(n) + 1 for the while loop of your isprime function.

So you should have:

def isprime(n):
    x=2
    while x < sqrt(n) +1:
        if n % x == 0:
            return False
        else:
            x += 1
    return True
schilippe
  • 81
  • 3
1

As others have pointed out:

  • You should increment primesFound, not primeList.
  • The isprime() function has a bug -- and returns True for 9. You need sqrt(n) + 1.

In addition:

  • You need to initialize i outside the while loop; otherwise, you simply build up a list of 2's.
  • There is no need for primesFound. Just check len(primeList).

And my pet peeve:

  • Command-line programs should resort to interactive user input only in special circumstances. Where possible, take parameters as command-line arguments or options. For example: userinput = int(sys.argv[1]).
FMc
  • 39,513
  • 12
  • 72
  • 131
1

To get n numbers that satisfy some condition, you could use itertools.islice() function and a generator expression:

from itertools import count, islice

n = int(raw_input('number of primes:'))
primes = list(islice((p for p in count(2) if isprime(p)), n))

where (p for p in count(2) if isprime(p)) is a generator expression that produces prime numbers indefinitely (it could also be written as itertools.ifilter(isprime, count(2))).

You could use Sieve of Eratosthenes algorithm, to get a more efficient solution:

def primes_upto(limit):
    """Yield prime numbers less than `limit`."""
    isprime = [True] * limit
    for n in xrange(2, limit):
        if isprime[n]:
           yield n
           for m in xrange(n*n, limit, n): # mark multiples of n as composites
               isprime[m] = False

print list(primes_upto(60))
# -> [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59]

See Fastest way to list all primes below N in python.

Note: there are about limit / (log(limit) - 1) prime numbers less than limit.

You could also use an infinite prime number generator such as gen_primes(), to get the first n primes numbers:

primes = list(islice(gen_primes(), n))

See How to implement an efficient infinite generator of prime numbers in Python?

Community
  • 1
  • 1
jfs
  • 346,887
  • 152
  • 868
  • 1,518
0
def is_prime(n):
    x=2
    while x < sqrt(n) +1:
        if n % x == 0:
            return False
            break
        else:
            x += 1
    return True
Simon Adcock
  • 3,448
  • 3
  • 23
  • 41