1. Home

Python Tutorials - Elevate Your Coding Skills with Comprehensive Tutorials

Discover Python tutorials covering everything from the basics to advanced topics. Whether you're new to programming or looking to level up your skills, our tutorials will guide you every step of the way

• 201 Lessons
• 33 Hours
156

# Prime Number Program in Python

Updated on 24/07/202412,390 Views

## Introduction

Are you interested in learning how to write a Python program that tests whether or not a given quantity is a prime number? We can write a program in Python to verify whether a given integer is prime. Python is an versatile and powerful programming language that is easy to learn. It offers high-level data structures that are incredibly efficient and a primitive but effective object-oriented approach to programming. Follow this tutorial for more insights.

## Overview

Python is a popular programming language that supports three numeric data types: int, float, and complex. This tutorial will focus on constructing a prime number program in Python. Before getting into the code, learning the basics of numbers and math in Python is vital. Python supports mathematical operations such as addition, subtraction, multiplication, and division. You may also round numbers to a particular number of decimal places and format and display numbers in strings. Several methods exist to achieve this, such as using a for loop to run over all the integers from 2 to (N/2), testing whether it divides N, or using the math module to optimize the program. We may also write a program to acquire a sequence of prime numbers less than or equal to a specified value.

## What is a Prime Number?

A prime number is any natural number that has greater value than 1 and prime numbers can only be divided by itself or 1. A prime number is not a product of two lesser natural numbers. For example, 5 is a prime number since it can only be divided by 1 and 5, but 6 is not a prime number because it can be divided by 1, 2, 3, and 6. The first 10 prime numbers are 2, 3, 5, 7, 11, 13, 17, 19, 23, and 29. Numbers that include more than two elements are termed composite numbers. The number 1 is neither prime nor composite. A well-structured prime number program in C or Python can efficiently generate a list of prime numbers within a specified range.

## Basic Program For Checking Prime Number in Python

Here's a basic Python program to check if a given number is prime or not using a loop:

Code:

`def is_prime(number):    if number <= 1:        return False    for i in range(2, int(number**0.5) + 1):        if number % i == 0:            return False    return True# Test the functionnum = 17if is_prime(num):    print(f"{num} is a prime number.")else:    print(f"{num} is not a prime number.")`

## Finding Prime Numbers with a Flag Variable

In this program, we use a flag variable to keep track of whether a number is prime or not. We print all prime numbers within a given range.

Code:

`def is_prime(number):    if number <= 1:        return False    for i in range(2, int(number**0.5) + 1):        if number % i == 0:            return False    return Truestart = 10end = 50for num in range(start, end+1):    if is_prime(num):        print(num, end=" ")`

## Checking Prime Numbers Using Recursion:

Here's a recursive function to check if a number is prime:

Code:

`def is_prime(n, i=2):    if n <= 2:        return n == 2    if n % i == 0:        return False    if i * i > n:        return True    return is_prime(n, i + 1)# Test the functionnum = 17if is_prime(num):    print(f"{num} is a prime number.")else:    print(f"{num} is not a prime number.")`

## Checking Prime Numbers Using sympy.isprime() method

The sympy library provides an isprime() method for checking prime numbers:

Code:

`import sympynum = 29if sympy.isprime(num):    print(f"{num} is a prime number.")else:    print(f"{num} is not a prime number.")`

## Check Prime Numbers Using the Trial Division Method

The trial division method checks if a number is prime by dividing it by all numbers from 2 to the square root of the number.

Code:

`def is_prime_trial_division(number):    if number <= 1:        return False    if number <= 3:        return True    if number % 2 == 0 or number % 3 == 0:        return False    i = 5    while i * i <= number:        if number % i == 0 or number % (i + 2) == 0:            return False        i += 6    return True# Test the functionnum = 29if is_prime_trial_division(num):    print(f"{num} is a prime number.")else:    print(f"{num} is not a prime number.")`

## Checking Prime Numbers Using a While Loop

In this program, we use a while loop to check divisibility and determine if a number is prime or not.

Code:

`def is_prime_while_loop(number):    if number <= 1:        return False    if number <= 3:        return True    if number % 2 == 0 or number % 3 == 0:        return False    i = 5    while i * i <= number:        if number % i == 0 or number % (i + 2) == 0:            return False        i += 6    return True# Test the functionnum = 37if is_prime_while_loop(num):    print(f"{num} is a prime number.")else:    print(f"{num} is not a prime number.")`

## Check Prime Numbers Using the Math Module

The math module provides a sqrt() function that can be used to optimize prime checking.

Code:

`import mathdef is_prime_with_math(number):    if number <= 1:        return False    if number <= 3:        return True    if number % 2 == 0 or number % 3 == 0:        return False    for i in range(5, int(math.sqrt(number)) + 1, 6):        if number % i == 0 or number % (i + 2) == 0:            return False    return True# Test the functionnum = 41if is_prime_with_math(num):    print(f"{num} is a prime number.")else:    print(f"{num} is not a prime number.")`

## Prime Number Generator Using a Generator Function

This example creates a generator function that generates prime numbers indefinitely.

Code:

`def prime_generator():    yield 2    primes = [2]    current_number = 3    while True:        is_prime = all(current_number % prime != 0 for prime in primes)        if is_prime:            primes.append(current_number)            yield current_number        current_number += 2# Generate and print the first 10 prime numbersgenerator = prime_generator()for _ in range(10):    print(next(generator))`

## Prime Factorization

This program calculates and prints the prime factors of a given number.

Code:

`def prime_factors(n):    factors = []    divisor = 2    while n > 1:        while n % divisor == 0:            factors.append(divisor)            n //= divisor        divisor += 1    return factorsnumber = 72factors = prime_factors(number)print(f"Prime factors of {number}: {factors}")`

## Sieve of Eratosthenes

The Sieve of Eratosthenes is an efficient algorithm to find all prime numbers up to a given limit.

Code:

`def sieve_of_eratosthenes(limit):    sieve = [True] * (limit + 1)    sieve[0:2] = [False, False]    p = 2    while p * p <= limit:        if sieve[p]:            for i in range(p * p, limit + 1, p):                sieve[i] = False        p += 1    primes = [i for i, is_prime in enumerate(sieve) if is_prime]    return primes# Find and print all prime numbers up to 50limit = 50primes = sieve_of_eratosthenes(limit)print(f"Prime numbers up to {limit}: {primes}")`

## Conclusion

The primary idea behind determining prime numbers through a Python program is to divide the input number by all the integers to see whether there are other positive divisors besides 1 and the input number. You can discover whether a given number is prime by practicing the technique in Python. It is vital to underline that prime numbers have a unique feature that makes them relevant in various domains, including number theory, computer science, and cryptography. This tutorial will help you discover numerous strategies for obtaining prime numbers in Python and understand their challenges.

## FAQs

1. How to write a Python program to find prime numbers in a list?

To write a Python program to find prime numbers in a list, you may iterate through the list and, for each number, check if it is more than 1 and if it is divisible by any integer between 2 and the square root of the number plus one, and if not, add it to a new list of prime numbers.

2. How to write a Python program to print prime numbers less than 20?

You can develop a Python program to output prime integers smaller than 20 by constructing a loop that iterates over numbers, testing each for primality and publishing the prime ones.

3. What is the fastest way to check if a number is prime Python?

The most efficient approach to verify if a number is prime in Python is to use the O(sqrt(N)) technique, which entails iterating from 2 to the integer value of the square root of the number and testing if the number is divisible by any of those values.

4. How do I write a factorial program in Python?

Use a for loop that iterates from 1 to the supplied number and multiply the loop control variable at each step by a variable that records the result of the factorial of the given number to develop a factorial program in Python. Alternatively, use a recursive function that calculates the factorial of a given number by multiplying it by the factorial of its preceding number until it reaches the base case of 1.

5. How to print prime numbers from 1 to 100 in Python using the function?

In Python, to find prime numbers in the range from 1 to 100 using a function that validates the primality of each number and then produces the prime numbers inside that range.

Director of Engineering

Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working …Read More

###### Get Free Career Counselling
+91
*
By clicking, I accept theT&Cand
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.

Talk to our experts. We’re available 24/7.

Indian Nationals

1800 210 2020

Foreign Nationals

+918045604032

## Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...