Prime Number Program in Python

Nitika Sharma 30 Jan, 2024 • 8 min read

For decades, mathematicians have been captivated by prime numbers—those elusive integers that can only be divided by one and themselves. In addition to their theoretical importance, prime numbers are essential to contemporary technology, cryptography, and algorithmic optimization. In this article, we explore the basic ideas behind Prime Number Program in Python, their identification, develop effective prime-checking routines, enhance prime creation, and drill into practical applications.

Prime Number Program in Python

Writing a Python Function to Check if a Number is Prime

def is_prime(n):

    if n <= 1:

        return False

    if n <= 3:

        return True

    if n % 2 == 0 or n % 3 == 0:

        return False

    i = 5

    while i * i <= n:

        if n % i == 0 or n % (i + 2) == 0:

            return False

        i += 6

    return True

Step-by-Step Explanation of the Code

 

Special Cases Handling

  • The function returns False if the input value ‘n’ is 1. 
  • The reason for this is that prime numbers are greater than one. Therefore, no number less than or equal to 1 can be a prime number.
  • If n is 2 or 3, it returns True. These are the smallest prime numbers, and they are prime by definition.

 

Divisibility by 2 and 3

  • Then modulo operator (%) is used to check whether ‘n’ is divisible by 2 or 3. ‘
  • n’ is not a prime number if it has divisors other than 1 and itself and is divisible by either 2 or 3. In this case, it returns False.

 

Loop to Check Other Divisors

  • After handling the special cases and basic divisibility checks, the code enters a loop to check for divisibility by other potential divisors.
  • The loop starts with ‘i’ initialized to 5. We start with 5 because we have already checked divisibility by 2 and 3.
  • As long as i i is n, the loop will continue. This is an approximation as ‘n’ should be divisible by a lower integer if it is divisible by a number higher than its square root.
  • Using the modulo operator, it determines during the loop if n is divisible by i or i + 2
  • All prime numbers above 3 can be represented as 6k ± 1, where k is a non-negative integer. So, we only need to check divisibility by form 6k ± 1 numbers.
  • If n is divisible by either i or i + 2, the function returns False because it has found a divisor other than 1 and n itself.

 

Returning the Result

When the code reaches this stage, n has successfully passed all tests to determine its divisibility and cannot be divided by any possible factors. As a result, it gives the result True, proving that n is a prime number.

Handling Special Cases (0, 1, and Negative Numbers)

The code handles special cases in the following manner:

  • It returns False if n is less than or equal to 1, correctly indicating that these integers are not prime.
  • And if n is 2 or 3, the function returns True.

The code does not specifically handle negative numbers but relies on the other checks. Negative numbers

Determining Prime Numbers

Prime numbers greater than 1 have the special characteristic of only having two distinct divisors: themselves and 1. 

You must ensure a number cannot be divided by any other positive integers besides these two to determine if it is a prime. Even numbers greater than 2 are not considered primes in this crucial procedure, and divisibility rules simplify identification. 

Also Read: Top 10 Uses of Python in the Real World with Examples

The Basic Principles of Checking for Prime Numbers

The fundamental concept of a prime number—a positive integer bigger than 1 with precisely two different positive divisors, 1 and itself—lays the foundation for the basic approach of checking for prime numbers. 

One must consider a number’s divisibility to determine if it is prime. This entails determining if the number can be divided by any positive integer other than 1 and itself in an equal amount. 

Divisibility Rules for Prime Numbers

This table summarizes key criteria and methods for identifying prime and composite numbers: 

CriteriaDescriptionExample
Divisibility by 2 or 3Check if the number is divisible by 2 or 3. If yes, it is not prime.6 (divisible by 2 and 3)
Numbers Ending in 5 or 0Any number ending in 5 or 0 (except 5 itself) is not prime. These numbers are divisible by 5. 25 is not prime because it can be divided by 5 (25 ÷ 5 = 5).
Iterate through Potential DivisorsStart with 5 and increment by 6 in each step. Check divisibility by both i and i + 2 for i starting from 5. Continue until i * i is greater than the number being checked.29 (not divisible by 5 or 7)
Square Root OptimizationOptimize the checking process by iterating only up to the square root of the number. If no divisors are found within this range, the number is prime.17 (no divisors found up to √17)
ResultIf the number survives all divisibility checks and no divisors are found up to its square root, it is prime. If it has divisors other than 1 and itself, it is composite.23 (prime), 9 (composite)

will return False if divisible by 2 or 3, and they will follow the same loop for other divisors. 

Optimizing the Prime Number Check

Introduction to Optimization Techniques for Prime Checking

  • While the basic prime number check we discussed earlier is functional, it may not be the most efficient method, especially when dealing with a large range of numbers. 
  • Fortunately, optimization techniques are available to improve the efficiency of prime checking. One of the most notable methods is the Sieve of Eratosthenes algorithm.

Sieve of Eratosthenes Algorithm for Finding Prime Numbers in Python

The Sieve of Eratosthenes is an ancient and efficient algorithm for finding all prime numbers up to a specified limit. It eliminates multiples of each prime number as it iterates through the numbers in a given range, leaving only the prime numbers behind. Let’s implement and explain the Sieve of Eratosthenes algorithm in Python:

def sieve_of_eratosthenes(limit):

    sieve = [True] * (limit + 1)

    sieve[0] = sieve[1] = False  # 0 and 1 are not prime

    for current in range(2, int(limit ** 0.5) + 1):

        if sieve[current]:

            for multiple in range(current * current, limit + 1, current):

                sieve[multiple] = False

    primes = [i for i, is_prime in enumerate(sieve) if is_prime]

    return primes

# Example usage:

limit = int(input("Enter the limit to find prime numbers up to: "))

prime_list = sieve_of_eratosthenes(limit)

print("Prime numbers up to {}: {}".format(limit, prime_list))

How the Code Works?

  1. We start by creating a list called sieve of Boolean values, with each element initially set to True. The list represents numbers from 0 to the specified limit.
  1. 0 and 1 are not prime numbers, we explicitly set sieve[0] and sieve[1] to False.
  1. Starting with ‘2’ (the first prime number), the procedure loops over all the numbers up to the square root of the limit.
  1. For each current prime number found, it marks all of its multiples as non-prime by setting the corresponding elements in the sieve list to False. This is done in the nested loop.
  1. After marking multiples of all prime numbers, we extract the prime numbers from the sieve list using a list comprehension. The indices where the corresponding element is True represent prime numbers.
  1. The program then prints the list of prime numbers up to the chosen limit.

Implementing the Sieve of Eratosthenes in Python

def sieve_of_eratosthenes(limit):

    sieve = [True] * (limit + 1)

    sieve[0] = sieve[1] = False # 0 and 1 are not prime

    for current in range(2, int(limit ** 0.5) + 1):

        if sieve[current]:

            for multiple in range(current * current, limit + 1, current):

                sieve[multiple] = False

    primes = [i for i, is_prime in enumerate(sieve) if is_prime]

    return primes

Generating Prime Numbers

Now that we have an optimized prime checking function and an understanding of the Sieve of Eratosthenes algorithm, let’s write a Prime Number Program in Python to generate a list of prime numbers within a given range. We’ll utilize the optimized prime-checking function and display the list of prime numbers.

def is_prime(n):

    if n <= 1:

        return False

    if n <= 3:

        return True

    if n % 2 == 0 or n % 3 == 0:

        return False

    i = 5

    while i * i <= n:

        if n % i == 0 or n % (i + 2) == 0:

            return False

        i += 6

    return True

def generate_primes_in_range(start, end):

    if start < 2:

        start = 2

# Adjust the lower bound to 2 if it’s less than that

primes = []

    for num in range(start, end + 1):

        if is_prime(num):

            primes.append(num)

    return primes

# Example usage:

start_range = 10

end_range = 50

prime_list = generate_primes_in_range(start_range, end_range)

print("Prime numbers between {} and {}: {}".format(start_range, end_range, prime_list))

This program efficiently generates and displays prime numbers within the user-specified range while handling invalid inputs efficiently.

Error Handling and Validation

Error handling and input validation are crucial to writing robust and reliable Python programs. Let’s enhance our prime number program in Python generation by adding error handling and validating user inputs to ensure they are positive integers. 

def is_prime(n):

    if n <= 1:

        return False

    if n <= 3:

        return True

    if n % 2 == 0 or n % 3 == 0:

        return False

    i = 5

    while i * i <= n:

        if n % i == 0 or n % (i + 2) == 0:

            return False

        i += 6

    return True

def generate_primes_in_range(start, end):

Validate user inputs

if not isinstance(start, int) or not isinstance(end, int) or start < 0 or end < 0:

        raise ValueError("Both 'start' and 'end' must be positive integers.")

    if start > end:

        raise ValueError("'start' must be less than or equal to 'end'.")

    if start < 2:

        start = 2 # Adjust the lower bound to 2 if it's less than that

    primes = []

    for num in range(start, end + 1):

        if is_prime(num):

            primes.append(num)

    return primes 

Example Usage with Error Handling

try:

    start_range = int(input("Enter the start of the range: "))

    end_range = int(input("Enter the end of the range: "))

    prime_list = generate_primes_in_range(start_range, end_range)

    print("Prime numbers between {} and {}: {}".format(start_range, end_range, prime_list))

except ValueError as e:

    print(f"Error: {e}")

except Exception as e:

    print(f"An unexpected error occurred: {e}")

How the Code Works?

  • We have added input validation to ensure that both the start and end are positive integers. 
  • A ValueError is raised with an appropriate error message if any of these conditions are not met.
  • We also check that the start is less than or equal to the end. 
  • If the start is greater than the end, a ValueError is raised.
  • The try block captures any potential exceptions that might occur during user input or prime number generation.
  • If a ValueError is raised due to invalid inputs, we catch it and display the error message.
  • If any other unexpected exception occurs, it is caught in the except Exception as an e-block, and an error message is displayed.

Conclusion

We hope you can now write prime number program in Python! Prime numbers are captivating mathematical entities and integral components of modern technology, cryptography, and security. If you’re eager to take your Python skills to the next level and delve into more advanced topics, consider enrolling in our Free Python Course.

Frequently Asked Questions

Q1. How do you write a prime number code in Python? 

A. To write a prime number code in Python, use a loop to check divisibility for each number, typically starting from 2 up to the number you want to test.

Q2. How do you find the prime number in Python? 

A. To find prime numbers in Python, use a loop to iterate through numbers, checking each for primality by testing divisibility. Refer to the table mentioned above in the artilce.

Q3. Is there a prime number function in Python? 

A. Python doesn’t have a built-in prime number function, but you can create one by defining a custom function to check for primality.

Q4. How do you get prime numbers from a string in Python? 

A. To get prime numbers from a string in Python, you’d first need to extract numbers from the string, then apply prime-checking logic to each extracted number using a loop or a list comprehension.

Nitika Sharma 30 Jan 2024

Frequently Asked Questions

Lorem ipsum dolor sit amet, consectetur adipiscing elit,

Responses From Readers

Related Courses

image.name
0 Hrs 70 Lessons
5

Introduction to Python

Free