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:
Find Prime number just less than and just greater each element of given Array
Next article icon

Analysis of Different Methods to find Prime Number in Python

Last Updated : 18 Oct, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

If you participate in competitive programming, you might be familiar with the fact that questions related to Prime numbers are one of the choices of the problem setter. Here, we will discuss how to optimize your function which checks for the Prime number in the given set of ranges, and will also calculate the timings to execute them.

Going by definition, a Prime number is a positive integer that is divisible only by itself and 1. For example: 2,3,5,7. But if a number can be factored into smaller numbers, it is called a Composite number. For example: 4=2*2, 6=2*3

And the integer 1 is neither a prime number nor a composite number. Checking that a number is prime is easy but efficiently checking needs some effort.

Method 1:

Let us now go with the very first function to check whether a number, say n, is prime or not. In this method, we will test all divisors from 2 to n-1. We will skip 1 and n. If n is divisible by any of the divisor, the function will return False, else True. Following are the steps used in this method: 

  1. If the integer is less than equal to 1, it returns False.
  2. If the given number is divisible by any of the numbers from 2 to n, the function will return False
  3. Else it will return True

Python3




# Python Program to find prime numbers in a range
import math
import time
def is_prime(n):
    if n <= 1:
        return False
    if n % 2 == 0:
        return n == 2
 
    max_div = math.floor(math.sqrt(n))
    for i in range(3, 1 + max_div, 2):
        if n % i == 0:
            return False
    return True
 
# Driver function
t0 = time.time()
c = 0 #for counting
 
for n in range(1,100000):
    x = is_prime(n)
    c += x
print("Total prime numbers in range :", c)
 
t1 = time.time()
print("Time required :", t1 - t0)
 
 

Output: 

Total prime numbers in range: 9592 Time required: 60.702312707901

In the above code, we check all the numbers from 1 to 100000 whether those numbers are prime or not. It has a huge runtime as shown. It takes around 1 minute to run. This is a simple approach but takes a lot of time to run. So, it is not preferred in competitive programming.

Method 2:

 
In this method, we use a simple trick by reducing the number of divisors we check for. We have found that there is a fine line which acts as the mirror as shows the factorization below the line and factorization above the line just in reverse order. The line which divided the factors into two halves is the line of the square root of the number. If the number is a perfect square, we can shift the line by 1 and if we can get the integer value of the line which divides. 

36=1*36             =2*18   =3*12   =4*9 ------------   =6*6 ------------   =9*4   =12*3   =18*2   =36*1

In this function, we calculate an integer, say max_div, which is the square root of the number and get its floor value using the math library of Python. In the last example, we iterate from 2 to n-1. But in this, we reduce the divisors by half as shown. You need to import the math module to get the floor and sqrt function. 
Following are the steps used in this method: 

  1. If the integer is less than equal to 1, it returns False.
  2. Now, we reduce the numbers which needs to be checked to the square root of the given number.
  3. If the given number is divisible by any of the numbers from 2 to the square root of the number, the function will return False
  4. Else it will return True

Python3




# Python Program to find prime numbers in a range
import time
def SieveOfEratosthenes(n):
      
    # Create a boolean array "prime[0..n]" and
    # initialize all entries it as true. A value
    # in prime[i] will finally be false if i is
    # Not a prime, else true.
    prime = [True for i in range(n+1)]
     
    p = 2
    while(p * p <= n):
          
        # If prime[p] is not changed, then it is
       # a prime
        if (prime[p] == True):
              
            # Update all multiples of p
            for i in range(p * p, n + 1, p):
                prime[i] = False
        p += 1
    c = 0
 
    # Print all prime numbers
    for p in range(2, n):
        if prime[p]:
            c += 1
    return c
 
# Driver function
t0 = time.time()
c = SieveOfEratosthenes(100000)
print("Total prime numbers in range:", c)
 
t1 = time.time()
print("Time required:", t1 - t0)
 
 

Output:  

Total prime numbers in range: 9592 Time required: 0.4116342067718506

In the above code, we check all the numbers from 1 to 100000 whether those numbers are prime or not. It takes comparatively lesser time than the previous method. This is a bit tricky approach but makes a huge difference in the runtime of the code. So, it is more preferred in competitive programming. 
 

Method 3:

 
Now, we will optimize our code to next level which takes lesser time than the previous method. You might have noticed that in the last example, we iterated through every even number up to the limit which was a waste. The thing to notice is that all the even numbers except two can not be prime number. In this method, we kick out all the even numbers to optimize our code and will check only the odd divisors. 
Following are the steps used in this method: 

  1. If the integer is less than equal to 1, it returns False.
  2. If the number is divisible by 2, it will return True if the number is equal to 2 else false.
  3. Now, we have checked all the even numbers. Now, look for the odd numbers.
  4. If the given number is divisible by any of the numbers from 3 to the square root of the number skipping all the even numbers, the function will return False
  5. Else it will return True

Python3




 
 

Output:  

Total prime numbers in range: 9592 Time required : 0.11761713027954102

In the above code, we check all the numbers from 1 to 100000 whether those numbers are prime or not. It takes comparatively lesser time than all the previous methods for running the program. It is most efficient and quickest way to check for the prime number. Therefore, it is most preferred in competitive programming. Next time while attempting any question in competitive programming, use this method for best results.
 

Sieve Method: 

This method prints all the primes smaller than or equal to a given number, n. For example, if n is 10, the output should be “2, 3, 5, 7”. If n is 20, the output should be “2, 3, 5, 7, 11, 13, 17, 19”. 
This method is considered to be the most efficient method to generate all the primes smaller than the given number, n. It is considered as the fastest method of all to generate a list of prime numbers. This method is not suited to check for a particular number. This method is preferred for generating the list of all the prime numbers.

Python3




# Python Program to find prime numbers in a range
import time
def SieveOfEratosthenes(n):
      
    # Create a boolean array "prime[0..n]" and
    # initialize all entries it as true. A value
    # in prime[i] will finally be false if i is
    # Not a prime, else true.
    prime = [True for i in range(n+1)]
     
    p = 2
    while(p * p <= n):
          
        # If prime[p] is not changed, then it is
       # a prime
        if (prime[p] == True):
              
            # Update all multiples of p
            for i in range(p * p, n + 1, p):
                prime[i] = False
        p += 1
    c = 0
 
    # Print all prime numbers
    for p in range(2, n):
        if prime[p]:
            c += 1
    return c
 
# Driver function
t0 = time.time()
c = SieveOfEratosthenes(100000)
print("Total prime numbers in range:", c)
 
t1 = time.time()
print("Time required:", t1 - t0)
 
 

Output: 

Total prime numbers in range: 9592 Time required: 0.0312497615814209

Note : Time required for all the procedures may vary depending on the compiler but the order of time required by the different methods will remain same.

Reference : 

\https://www.geeksforgeeks.org/sieve-of-eratosthenes/ 
http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes 

 



Next Article
Find Prime number just less than and just greater each element of given Array
https://media.geeksforgeeks.org/auth/avatar.png
GeeksforGeeks
Improve
Article Tags :
  • DSA
  • Mathematical
  • Python
  • Prime Number
Practice Tags :
  • Mathematical
  • Prime Number
  • python

Similar Reads

  • Different Methods to Check if a Number is Prime
    Prime numbers are the natural numbers greater than 1, that have no positive divisors other than 1 and itself. In other words, a prime number can only be divided evenly (without a remainder) by 1 and the number itself. We can also use the following calculator to check if any number is prime or compos
    5 min read
  • Find all the prime numbers of given number of digits
    Given an integer D, the task is to find all the prime numbers having D digits. Examples: Input: D = 1 Output: 2 3 5 7 Input: D = 2 Output: 11 13 17 19 23 29 31 37 41 43 47 53 61 67 71 73 79 83 89 97 Approach: Numbers with D digits lie in the range [10(D - 1), 10D - 1]. So, check all the numbers in t
    5 min read
  • Find product of prime numbers between 1 to n
    Given a number n, we need to find the product of all prime numbers between 1 to n.Examples: Input: 5Output: 30Explanation: product of prime numbers between 1 to 5 is 2 * 3 * 5 = 30 Input : 7Output : 210 Approach: Basic brute-force method Steps: Initialize the product to be 1 and an empty list of pri
    11 min read
  • Check if a number is a Pythagorean Prime or not
    Given a positive integer N, check if it is Pythagorean prime or not. If it is a Pythagorean prime, print 'Yes' otherwise print 'No'.Pythagorean primes : A prime number of the form 4*n + 1 is a Pythagorean prime. It can also be expressed as sum of two squares. Pythagorean primes in the range 1 - 100
    6 min read
  • Find Prime number just less than and just greater each element of given Array
    Given an integer array A[] of size N, the task is to find the prime numbers just less and just greater than A[i] (for all 0<=i<N). Examples: Input: A={17, 28}, N=2Output:13 1923 29Explanation:13 is the prime number just less than 17.19 is the prime number just greater than 17.23 is the prime n
    15+ min read
  • Finding n-th number made of prime digits (2, 3, 5 and 7) only
    Given a number 'n', find the nth number whose each digit is a prime number i.e 2, 3, 5, 7. . . In other words, find the nth number of this sequence. 2, 3, 5, 5, 22, 23...... Given that the nth number such found will be less than equal to 10^18 Examples : Input: 10Output: 3Explanation: 2, 3, 5, 7, 22
    15+ min read
  • Find count of Almost Prime numbers from 1 to N
    Given a number N. Find number of almost primes from 1 to [Tex]n[/Tex]. A number is called almost if it has exactly two distinct prime factors. Note: The numbers can have any number of non-prime factors but should have exactly two prime factors. Examples: Input : N = 10Output : 2Explanation : 6, 10 a
    10 min read
  • Sum of every K’th prime number in an array
    Given an integer k and an array of integers arr (less than 10^6), the task is to find the sum of every k’th prime number in the array. Examples: Input: arr[] = {2, 3, 5, 7, 11}, k = 2 Output: 10 All the elements of the array are prime. So, the prime numbers after every K (i.e. 2) interval are 3, 7 a
    9 min read
  • Sum of every K'th prime number in an array
    Given an array of integers (less than 10^6), the task is to find the sum of all the prime numbers which appear after every (k-1) prime number i.e. every K'th prime number in the array. Examples: Input : Array : 2, 3, 5, 7, 11 ; n=5; k=2 Output : Sum = 10 Explanation: All the elements of the array ar
    7 min read
  • R program to find prime and composite numbers in an interval
    A natural number (1, 2, 3, 4, 5 and so on) is called a prime number if it is greater than 1 and cannot be written as the product of two smaller natural numbers. The numbers greater than 1 that are not prime are called composite numbers. A composite number is a positive integer that can be formed by
    7 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