How to Check if a Number is Prime in Python

79 views

How to Check if a Number is Prime in Python

How to Check if a Number is Prime in Python

I need to determine if a given number is prime. How can I write a function to check for prime numbers in Python?

solveurit24@gmail.com Changed status to publish February 16, 2025
0

A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. Here’s an efficient way to check for prime numbers:

  1. Handle Edge Cases:
    • Numbers less than 2 are not prime.
    • 2 is the only even prime number.
  2. Check for Divisors:
    • For numbers greater than 2, check divisibility up to the square root of the number.
  3. Code Example:

    def is_prime(n):
        if n <= 1:
            return False
        if n == 2:
            return True
        if n % 2 == 0:
            return False
        for i in range(3, int(n ** 0.5) + 1, 2):
            if n % i == 0:
                return False
        return True
    
    print(is_prime(11))  # Output: True
    


  4. Explanation:
    • The function is_prime checks if a number is prime.
    • It skips even numbers greater than 2 and only checks up to the square root for efficiency.
solveurit24@gmail.com Changed status to publish February 16, 2025
0