Why is this not returning 3 as a prime?

Question:

def isItPrime(n):
    p='true'
    if not n==2:
        for x in range(2,round(math.sqrt(n))+1):#I'm taking the square root to make the program more efficient, and adding the one so it doesn't create ranges like: range(2,2)
            if n%x==0:
                p='false'
                break
    return p

def findPrimes(n):
    primes=[]
    x=2 #if I change this value to 3 it does find 3 as a prime
    while len(primes)<n:
        if isItPrime(x)=='true':
            primes.append(x)
            x+=1
        x+=1
    return primes

print(isItPrime(3)) #true
print(findPrimes(10)) #[2, 5, 7, 11, 13, 17, 19, 23, 29, 31]

returns:
true,
[2, 5, 7, 11, 13, 17, 19, 23, 29, 31]
I don’t know what else to add here but it’s not letting me post until I add some more details

Asked By: BKTiv

||

Answers:

    if isItPrime(x)=='true':
        primes.append(x)
        x+=1
    x+=1

2 is a prime so it appends 2 to primes, then changes x to 3 then finishes the if then changes x to 4. Then starts the loop again.

Thus 3 is skipped.

Don’t increment x inside the if.

Answered By: Quentin
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.