1

I am trying to write a program that finds prime numbers.

prime = [2]
for k in range(3,100)
    if k%prime != 0
        prime.append(k)
print(prime)

When I run the program I get the error:

TypeError: unsupported operand type(s) for %: 'int' and 'list'

I think that the error arises when I try to divide by the list, but I am not really sure what to do. Any help would be appreciated.

  • `k%prime` you're trying to use modulo division with an int and a list. I'm not sure what you're trying to do, but that's not going to work. – Morgan Thrapp Jan 21 '16 at 19:48
  • replace prime = [2] with prime = 2 – Tobias Jan 21 '16 at 19:52
  • I figured that was the problem. I want to create a list with two in it, and then if it is a prime, append it to the prime list. I want to divide k by all the elements that are in the list. – S.Rodriguez Jan 21 '16 at 21:43

1 Answers1

0

You have to iterate through the whole prime list and make sure the modulus is nonzero for all items in the list

prime = [2]
for k in range(3,100):
    if all(k % p != 0 for p in prime):
        prime.append(k)

Optimized (don't check additional primes once a single prime factor has been found):

prime = [2]
for k in range(3,100):
    for p in prime:
        if k % p == 0:
            break
    else:
        prime.append(k)
Brendan Abel
  • 35,343
  • 14
  • 88
  • 118
  • You forgot a ":" after the first for! But thank you for your help! Also, I don't know what you mean by "the modulus is nonzero". Do you mean the integer "k"? – S.Rodriguez Jan 21 '16 at 22:00
  • I also am unsure of what the variable "p" means? Should it not be "prime"? – S.Rodriguez Jan 21 '16 at 22:02
  • The `%` operator is called the modulus operator. It gives the remainder after `x / y`. If `x % y == 0`, then that means `y` is a factor of `x`. Prime numbers don't have other factors besides themselves and 1, so if all the possible factors of a number have a non-zero modulus, the number has no factors and must be prime. – Brendan Abel Jan 21 '16 at 22:23
  • `for p in prime` is a loop. The same way `for k in range(3,200)` is a loop. `prime` is a list of prime numbers. `for p in prime` iterates through the list and sets `p` to one of the primes. It tests if any of the prime numbers in the `prime` list are factors of `k`. If `k` has no prime factors, it is a prime. – Brendan Abel Jan 21 '16 at 22:25
  • Okay that makes complete sense. Thank you for the help. – S.Rodriguez Jan 21 '16 at 22:32