Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is this not returning 3 as a prime?

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading