Introduction:
Prime numbers are natural numbers greater than 1 that have no positive divisors other than 1 and themselves. Determining whether a given number is prime or not is a common problem in mathematics and computer science. In this tutorial, we’ll learn how to write a Python program to check if a number is prime or not.

Understanding Prime Numbers:
Before diving into the implementation, let’s understand the concept of prime numbers. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. For example, 2, 3, 5, 7, 11, and 13 are prime numbers.

Approach to Check Primality:
To determine whether a number n is prime or not, we can follow the following approach:

  1. Check if the number is less than 2. If it is, it cannot be prime.
  2. Iterate from 2 to the square root of n (inclusive) and check if n is divisible by any of these numbers.
  3. If n is divisible by any number in this range, it is not prime. Otherwise, it is prime.

Python Implementation:

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

# Test the function
num = int(input("Enter a number: "))
if is_prime(num):
    print(num, "is a prime number")
else:
    print(num, "is not a prime number")

Explanation:

  • We define a function is_prime that takes an integer n as input.
  • We first check if n is less than 2. If it is, we return False because prime numbers are greater than 1.
  • We then iterate through the numbers from 2 to the square root of n (inclusive) using a for loop.
  • Inside the loop, we check if n is divisible by the current number (i). If it is, we return False because n is not prime.
  • If the loop completes without finding any divisors of n, we return True, indicating that n is prime.

Conclusion:
In this tutorial, we learned how to write a Python program to check if a given number is prime or not. Understanding prime numbers and implementing primality testing algorithms is essential in various mathematical and computational tasks. Happy coding!

By

Leave a Reply

Discover more from Geeky Codes

Subscribe now to keep reading and get access to the full archive.

Continue reading