Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
How to check NoneType in Python
Next article icon

Check Prime Number in Python

Last Updated : 10 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a positive integer N, the task is to write a Python program to check if the number is Prime or not in Python. For example, given a number 29, it has no divisors other than 1 and 29 itself. Hence, it is a prime number.

Note: Negative numbers (e.g. -13) are not considered prime number.

Using sympy.isprime() method

In the sympy module, we can test whether a given number n is prime or not using sympy.isprime() function. For n < 264 the answer is definitive; larger n values have a small probability of actually being pseudoprimes. Before using sympy module, we need to install it using this command:

pip install sympy
Python
from sympy import *  g1 = isprime(30) g2 = isprime(13) g3 = isprime(2)  print(g1)  print(g2)  print(g3)  

Output

False True True

Explanation:

  • isprime() function from the SymPy library checks if a number is prime or not.
  • It prints False for 30, True for 13 and True for 2 because 30 is not prime, while 13 and 2 are prime numbers.

Using Math Module

The code implements a basic approach to check if a number is prime or not, by traversing all the numbers from 2 to sqrt(n)+1 and checking if n is divisible by any of those numbers. 

Python
import math  n = 11 if n <= 1:     print(False) else:     is_prime = True     for i in range(2, int(math.sqrt(n)) + 1):         if n % i == 0:             is_prime = False             break     print(is_prime) 

Output
True 

Explanation:

  • Check if n <= 1, if true, it’s not prime.
  • Loop from 2 to the square root of n, if n % i == 0, it’s not prime. If no divisors found, n is prime.

Using Flag Variable

Instead of checking till n, we can check till √n because a larger factor of n must be a multiple of a smaller factor that has been already checked. Now let’s see the code for the first optimization method

Python
from math import sqrt  n = 17 p_fl = 0  if(n > 1):     for i in range(2, int(sqrt(n)) + 1):         if (n % i == 0):             p_fl = 1             break     if (p_fl == 0):         print("True")     else:         print("False") else:     print("False") 

Output
True 

Explanation:

  • If n is greater than 1, it loops from 2 to the square root of n to check if any number divides n evenly.
  • If any divisor is found, the p_fl is set to 1, indicating n is not prime. If no divisors are found, it prints “True” (meaning n is prime). Otherwise, it prints “False”.
  • If n <= 1, it directly prints “False” since numbers less than or equal to 1 are not prime.

Using Miller-Rabin Primality Test

We can use the Miller-Rabin Primality Test, a probabilistic method, to check if a number is prime by performing multiple rounds of testing, where each test verifies if a randomly chosen base witnesses the compositeness of the number.

Python
import random  n = 30 k = 5  if n <= 1:     print(False) elif n <= 3:     print(True) elif n % 2 == 0:     print(False) else:     d = n - 1     while d % 2 == 0:         d //= 2      is_prime = True     for _ in range(k):         a = random.randint(2, n - 2)         x = pow(a, d, n)                  if x == 1 or x == n - 1:             continue                  while d != n - 1:             x = (x * x) % n             d *= 2             if x == 1:                 is_prime = False                 break             if x == n - 1:                 break         if not is_prime:             break     print(is_prime)  n = 3 k = 5  if n <= 1:     print(False) elif n <= 3:     print(True) elif n % 2 == 0:     print(False) else:     d = n - 1     while d % 2 == 0:         d //= 2      is_prime = True     for _ in range(k):         a = random.randint(2, n - 2)         x = pow(a, d, n)                  if x == 1 or x == n - 1:             continue                  while d != n - 1:             x = (x * x) % n             d *= 2             if x == 1:                 is_prime = False                 break             if x == n - 1:                 break         if not is_prime:             break     print(is_prime) 

Output
False True 

Explanation:

  • Return False if n <= 1 or even, True if n <= 3.
  • Set d = n-1 and repeatedly divide by 2. Perform k iterations, picking a random base a and checking x = a^d % n.
  • If any test fails, return False; else, return True.

Using Recursion

We can also find the number prime or not using recursion. We can use the exact logic shown in method 2 but in a recursive way.

Python
from math import sqrt  def Prime(n, i):       if i == 1 or i == 2:           return True     if n % i == 0:           return False     if Prime(n, i - 1) == False:           return False      return True  n = 13 i = int(sqrt(n) + 1)  print(Prime(n, i)) 

Output
True 

Explanation:

  • Base condition: The recursion ends when the iterator i reaches 1 or 2, returning True because numbers 1 and 2 are prime.
  • Divisibility check: If n is divisible by i (i.e., n % i == 0), it returns False (meaning n is not prime).
  • Recursive call: The function calls itself with i – 1, checking for divisibility from i down to 2.
  • If the function finds no divisors by the time i reaches 2, it returns True, indicating the number is prime.

Recommended Artilce – Analysis of Different Methods to find Prime Number in Python



Next Article
How to check NoneType in Python

S

Shivam_k
Improve
Article Tags :
  • Python
  • Python Programs
  • Prime Number
  • python-basics
Practice Tags :
  • Prime Number
  • python

Similar Reads

  • Python Check If String is Number
    In Python, there are different situations where we need to determine whether a given string is valid or not. Given a string, the task is to develop a Python program to check whether the string represents a valid number. Example: Using isdigit() Method [GFGTABS] Python # Python code to check if strin
    6 min read
  • Check if a Number is a Whole Number in Python
    Floating-point numbers in Python can sometimes pose challenges when you need to determine whether they represent whole numbers. Due to the inherent precision limitations of floating-point representation, comparing them directly for equality with integers may lead to unexpected results. In this artic
    3 min read
  • Python | Check Numeric Suffix in String
    Sometimes, while programming, we can have such a problem in which we need to check if any string is ending with a number i.e it has a numeric suffix. This problem can occur in Web Development domain. Let's discuss certain ways in which this problem can be solved. Method #1: Using regex This problem
    6 min read
  • Python Program to Check Armstrong Number
    Given a number x, determine whether the given number is Armstrong number or not. A positive integer of n digits is called an Armstrong number of order n (order is number of digits) if. abcd... = pow(a,n) + pow(b,n) + pow(c,n) + pow(d,n) + .... Example: Input : 153 Output : Yes 153 is an Armstrong nu
    6 min read
  • How to check NoneType in Python
    The NoneType object is a special type in Python that represents the absence of a value. In other words, NoneType is the type for the None object, which is an object that contains no value or defines a null value. It is used to indicate that a variable or expression does not have a value or has an un
    2 min read
  • Perfect Number Program in Python
    A Perfect Number is a positive integer that is equal to the sum of its proper divisors, excluding the number itself. Example: 6 is a perfect number because its divisors (excluding itself) are 1, 2, and 3, and their sum is 6 (1 + 2 + 3 = 6).28 is a perfect number because its divisors are 1, 2, 4, 7,
    3 min read
  • Python Program to Check Number is a Power of Two
    we will discuss how to write a Python program to determine whether a given number is a power of two. A number is said to be a power of two if it can be expressed in the form of 2n, where n is a non-negative integer. Examples: [GFGTABS] Python def is_power_of_two(n): if n <= 0: return False return
    4 min read
  • Print all even numbers in a range - Python
    Our task is to print all even numbers within a given range. The simplest way to achieve this is by using a loop to iterate through the range and check each number for evenness. Let's explore some methods to do so. Using LoopWe can use a for loop with if conditional to check if a number is even. [GFG
    2 min read
  • Python program to check if number is palindrome (one-liner)
    In this article, we are given a number and we have to check whether the number is palindrome or not in one-liner code. The output will be True if it's a Palindrome number otherwise it would be False. Let's discuss how to find whether a number is palindrome or not in this article. Input1: test_number
    3 min read
  • Python Program to Check if a Number is Odd or Even
    Even Numbers are exactly divisible by 2 and Odd Numbers are not exactly divisible by 2. We can use modulo operator (%) to check if the number is even or odd. For even numbers, the remainder when divided by 2 is 0, and for odd numbers, the remainder is 1. In this article, we will learn how to check i
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences