简体   繁体   中英

How to determine prime number using recursion with single parameter Python

I am trying to create a function to determine whether a number is a prime number or not. However, I can only use one parameter in the function. Here is what I have so far, but I am not sure how to do the recursion part to make it return to the right value.

The question is "Write a recursive function "IsPrime(x)" to determine whether x (a positive integer) is a prime number or not. If it is prime, return True; otherwise, return False. The basic idea is that for all x >= 3, if x cannot be evenly divided by any prime integer less than or equal to sqrt(x), then it is a prime number. Again, do not use a built-in Python function. Instead, write your own code to achieve it."

def IsPrime(x):
    if x == 1:
        return False
    elif x == 2:
        return True
    else:
        return IsPrime(math.floor(math.sqrt(x)))

This is of course not the most efficient way to find prime numbers, but it can be done with recursion, by turning the "basic idea" you describe in the question into an algorithm:

  • If x >= 3, run through all integers i from 2 to sqrt(x):
    • Check if i is prime (using this function recursively).
      • If yes, check if x can be evenly divided by i.
        • If yes, then x is not a prime number (exit function).
        • If no, continue.
      • If no, continue.
  • If we have run through all i and the function is still running, then x was not divisible by any of the prime i, so x is a prime number.
import math

def IsPrime(x):
    if x == 1:
        return False
    if x == 2:
        return True
    for i in range(2, math.floor(math.sqrt(x)) + 1):
        if IsPrime(i):
            if x % i == 0:
                return False
    return True

Note that whenever a return statement is reached, the execution of the function is terminated. This allows us to omit the explicit else statement, for example.

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