简体   繁体   中英

python program to find prime number n by seeing if they can divide evenly into prime numbers less that the squareroot of n

How do I make this return the right results for primes less than 10 ?

from math import *

def isPrime(n):

i = [c for c in range(int(sqrt(n)),0,-1) if c % 2 != 0 and c > 1 ]

for x in i: 
    if n % x == 0:
        return print('%s is not prime' % (n))
return print('%s is prime number' %(n))


def main():

loopCnt = 'y'
while loopCnt != 'n':
    n = int(input('Enter a integer greater than 2: '))
    isPrime(n)


    loopCnt = input('Enter any key to try again or enter n to exit').strip().lower()


main()

It is not giving the desired output

i = [c for c in range(int(sqrt(n)),0,-1) if c % 2 != 0]

This code is skipping all even divisors. This is correct for most divisors, but it incorrectly skips 2, so it will misclassify even numbers!

You need to make an exception for 2, either in the filter or by adding a special case to check whether n is an even number greater than 2.

(As an aside, checking divisors in reverse order will slow you down. Small divisors are more common in randomly chosen composite numbers than large ones.)

Your error is that you exit the for loop in the first iteration always . You should only exit when you find it has a divisor, but otherwise you should keep looping. When you exit the loop without finding a divisor then is the time to return that fact.

So change:

for x in i: 
    if n % x == 0:
        return print('%s is not prime' % (n))
    else:
        return print('%s is prime number' %(n))

to:

for x in i: 
    if n % x == 0:
        return print('%s is not prime' % (n))
return print('%s is prime number' %(n))

Secondly, your i array includes the number 1, and since all numbers are dividable by 1 that does not make sense. So the range should stop before 1 instead of 0. Also, you should include 2 as a divider.

So change:

i = [c for c in range(int(math.sqrt(n)),0,-1) if c % 2 != 0]

By:

i = [c for c in range(int(math.sqrt(n)),1,-1) if c % 2 != 0] + [2]

See it in repl.it

As suggested by @Duskwolf, the line where you check for primes is wrong. A replacement function could simply be

import numpy as np

def isPrime(n):
    len = int(sqrt(n))
    divisors = np.zeros(len, dtype=np.bool)
    for i in range(1,len):
        if(n%(i+1)==0):
            divisors[i]=True
    prime = not divisors.any()
    if(prime):
        return print('%s is prime' % (n))
    return print('%s is not a prime number' %(n))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM