for i in range(2, 101):
for j in range(2, i):
if (i % j) == 0:
print(i,"is a composite number")
break
I tried making the if (i%j) != 0:
but then it wouldn't work (4 is not a prime number)
You can fix up your original algorithm like this:
for i in range(2, 101):
if all([(i % j) for j in range(2, i)]):
print(i,"is a prime number")
In general, you're probably better off using/learning from the established algorithms in cases like these. Here's a Python implementation of a well-known algorithm (the Sieve of Eratosthenes) for generating the first n
primes (credit to tech.io for the code):
def sieve(n):
primes = 2*[False] + (n-1)*[True]
for i in range(2, int(n**0.5+1.5)):
for j in range(i*i, n+1, i):
primes[j] = False
return [prime for prime, checked in enumerate(primes) if checked]
Some test output:
print(sieve(100))
[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]
The
for
loop you've used is correct for finding prime numbers. I would just another condition to it:if i > 1:
. Also, you would want to print the prime number