how to use for loop to calculate a prime number

2.5k Views Asked by At
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)

2

There are 2 best solutions below

3
On BEST ANSWER

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

for i in range(2, 101):
    if i > 1: # Prime numbers are greater than 1
        for j in range(2, i):
            if (i % j) == 0:
                print(i,"is a composite number")
                break
        else:
            print(i,"is a prime number")
0
On

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]