If you have any query feel free to chat us!
Happy Coding! Happy Learning!
To check if a number is prime in Python, you can create a function that determines whether the number has only two divisors (1 and itself). Here are two approaches to check for prime numbers:
- Using a Loop:
pythonCopy code
def is_prime(num): if num <= 1: return False for i in range(2, int(num**0.5) + 1): if num % i == 0: return False return True # Example usage: num_to_check = 17 if is_prime(num_to_check): print(f"{num_to_check} is a prime number.") else: print(f"{num_to_check} is not a prime number.")
Output:
csharpCopy code
17 is a prime number.
In this approach, the
is_prime()
function takes a positive integernum
as input. If the number is less than or equal to 1, it returnsFalse
, as prime numbers are greater than 1. It then checks for divisors from 2 up to the square root of the number (inclusive). If any divisor is found, the function returnsFalse
, indicating that the number is not prime. Otherwise, it returnsTrue
.
- Using Recursion:
pythonCopy code
def is_prime(num, divisor=2): if num <= 1: return False if divisor == num: return True if num % divisor == 0: return False return is_prime(num, divisor + 1) # Example usage: num_to_check = 17 if is_prime(num_to_check): print(f"{num_to_check} is a prime number.") else: print(f"{num_to_check} is not a prime number.")
The output for this example will also be:
csharpCopy code
17 is a prime number.
In this approach, the
is_prime()
function uses recursion to check for divisors. It has an additional parameterdivisor
that keeps track of the current divisor being checked. The function checks for the base cases (num <= 1 and divisor == num) and returnsFalse
orTrue
accordingly. If the number is divisible by the current divisor, it returnsFalse
, indicating that the number is not prime. Otherwise, it calls itself with the next divisor to check.Both approaches will correctly determine whether a given number is prime or not. You can use either of these methods based on your preference and the specific requirements of your code.
Comments: 0