简体   繁体   中英

Function to check if number x is prime in python

What I've done so far is:

def check_prime(x):
  if x >= 2:
    for n in range(2, x - 1):
      if x % n == 0:
        return False
      else:
        return True
  else:
    return False

However when I check if any number >= 2 is a prime it returns None instead of True or False . check_prime(0) returns False and check_prime(1) returns False . Why does any number >= 2 return None and how can I fix this.

Your function is wrong because you should not return True in the loop (in your code the loop will always run once).

def check_prime(x):
    if x >= 2:
        for n in range(2, x ):
            if (x % n) == 0:
                return False
        #after the complete for n loop
        return True
    else:
        return False

Checkout a working fiddle: http://pythonfiddle.com/check-prime

Besides all that you can obtimize your code (if you like) by taking the square root of x (round up) as the end point for your loop (do not forget +1 since range is not inclusive). Since you will get the mirrored options once your past the square root. (6×4 = 4*6 = 20. Square root of 20 is 5).

Problem 1: The problem is range(n, x-1) .

If your input is 2 or 3, range(2, x-1) will be an empty list since the second parameter of range is exclusive.

Since you're only returning inside the for loop and it never gets there, it returns None (ie it returns nothing).

Problem 2: Aside from never entering the for loop if x = 2 or x = 3 , your code has some issues.

As you've written it, it will return in the first iteration. Certainly, if x % n == 0 you know x is not prime and can return False . But even if n is not a factor of x , you still have to check the other potential factors.

You should return True outside of the for loop, not inside it.

Solution:

if x == 2: return True
if x%2 == 0 or x < 2: return False
for n in range(3, x/2, 2):
  if x % n == 0:
    return False
return True

Here is your fixed code. You had multiple issues in it, namely:

  1. When number was 2 for example, you went into the if cycle, however your loop did not execute and therefore you got None as a result.
  2. range(start, end) does not include the end , therefore you have do not have to write end - 1 .
  3. You need to check for every number up to n (well, you don't have to when you optimize your code :) ), however if I had a number like 99 = 3 * 33, it would not be divisible by 2 and would classify it as a prime despite being a composite number.

You can do a number of basic optimalizations such as check numbers up to sqrt(n) , check if number is divisble by 2 to discard half of the choices, etc.

'

def check_prime(x):
    for n in range(2, x):
        if x % n == 0:
            return False
    return True

Here's a kludge-tastic way of doing it...

def prime(x):

    factors = []
    if x <= 0:
        return False
    if x == 1:
        return False
    if x == 2:
        return True
    for n in range(2, x):
        if x % n == 0:
            factors.append(n)

    if len(factors) != 0:
        return False
    else:
        return True

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