0

I am trying to print out all prime numbers that are in an array called 'checkMe'. But I just can't get it to work. I've succesfully made a program that checks it for one number but it doesn't work for an array. If anyone knows what is wrong on please tell me. BTW: I am a big noob in python so it probably isn't the most beautiful code.

checkMe = range(1, 100)

dividers = []
primes = []

for y in checkMe:
    x = y
    for x in range(2, x):
        if (y/x).is_integer():
            dividers.append(x)
    if len(dividers) < 2:
        primes.append(y)

print("\n"+str(checkMe)+" has "+str(len(primes))+" primes")
print(primes)

Output:

range(1, 100) has 5 primes
[1, 2, 3, 4, 5]

Expected Output:

range(1, 100) has 25 primes
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83,
89, 97]
J0R1AN
  • 583
  • 7
  • 10
  • 1
    Possible duplicate of [Sieve of Eratosthenes - Finding Primes Python](https://stackoverflow.com/questions/3939660/sieve-of-eratosthenes-finding-primes-python) – Sean Pianka Oct 15 '18 at 16:33
  • Change this line in your code, `for x1 in range(2, x): if (y/x1).is_integer():` – Arihant Oct 15 '18 at 16:35

3 Answers3

2

I dont want to burst your bubble but if you were to have done some quick googling you could have found an answer.

Anyways the solution to your problem is as follows:

checkMe = range(1, 100)

dividers = []
primes = []

for num in range(2,100):
    prime = True
    for i in range(2,num):
        if (num%i==0):
            prime = False
            dividers.append(num)
    if prime:
        primes.append(num)

print("\n"+ str(checkMe)+ "has "+str(len(primes))+" primes")
print(primes)
giusti
  • 3,156
  • 3
  • 29
  • 44
B. Cratty
  • 1,725
  • 1
  • 17
  • 32
  • 1
    I don't think it is a reasonable criticism to say that they could have found the solution by googling. Algorithms are hard to learn and we are here to help. – rje Oct 15 '18 at 18:21
2

The logic is correct but you don't reset your divider array. Also you should ignore the number 1 and the number of divider should be less than 1.

this should work

checkMe = range(1, 100)
primes = []
for y in checkMe[1:]:
    x = y
    dividers = []
    for x in range(2, x):
        if (y/x).is_integer():
            dividers.append(x)
    if len(dividers) < 1:
        primes.append(y)
print("\n"+str(checkMe)+" has "+str(len(primes))+" primes")
print(primes)

Hope this helped you, bye

1

Please read the python docs there is a lot in there https://docs.python.org/3/tutorial/controlflow.html

check_me = range(2, 100)

primes = []
for i in check_me:
    for j in range(2, i):
        if not i % j:
            break
    else:
        primes.append(i)

print(f'{check_me} as {len(primes)} primes\n', *primes)
# range(2, 100) as 25 primes
# 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
vash_the_stampede
  • 4,590
  • 1
  • 8
  • 20