Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prime Numbers in Python

Tags:

python

primes

I was trying to write a program that would display the prime numbers between 2 and 200.

This is the program that i wrote.

liste = [ ]
liste.append(2)
liste = [2]

for primeCandidate in range (2,10):
    isPrime = True
    for divisor in range (2,primeCandidate):
        if primeCandidate % divisor == 0:
            isPrime = False
            break
        if isPrime:
            liste.append(primeCandidate)
            print(liste)

But I always get a wrong output. And I couldn't find my mistakes. Can you help me finding my mistakes?

like image 633
Ekrem Ipek Avatar asked Aug 17 '26 15:08

Ekrem Ipek


1 Answers

Two things leap out:

(1) You don't need to set liste to [2] at the start; your primeCandidate loop includes 2, so you'll get 2 twice if you do.

(2) Your "if isPrime" is one level too deep. You can only trust isPrime after you've checked the candidate divisors. (Well, you're actually checking more than you need, but that's only an efficiency issue, not a bug.) To be specific:

liste = []
for primeCandidate in range (2,100):
    isPrime = True
    for divisor in range (2,primeCandidate):
        if primeCandidate % divisor == 0:
            isPrime = False
            break
    if isPrime:
        liste.append(primeCandidate)
        print(liste)
like image 157
DSM Avatar answered Aug 20 '26 03:08

DSM