Prime Numbers - GeeksforGeeks

CoursesFor Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore MoreFor StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore MoreSchool CoursesSchool GuidePython ProgrammingLearn To Make AppsAll Courses
For Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More
LIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore More
DSA Live Classes
System Design
Java Backend Development
Full Stack LIVE
Explore More
Self-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More
DSA- Self Paced
SDE Theory
Must-Do Coding Questions
Explore More
For StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More
LIVECompetitive ProgrammingData Structures with C++Data ScienceExplore More
Competitive Programming
Data Structures with C++
Data Science
Explore More
Self-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More
DSA- Self Paced
CIP
JAVA / Python / C++
Explore More
School CoursesSchool GuidePython ProgrammingLearn To Make Apps
School Guide
Python Programming
Learn To Make Apps
All Courses
TutorialsPractice DS & Algo.Must Do QuestionsDSA Topic-wiseDSA Company-wiseAlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll AlgorithmsData StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data StructuresInterview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice QuizzesLanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlinCS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware EngineeringGATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CSWeb TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHPSoftware DesignsSoftware Design PatternsSystem Design TutorialSchool LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesCS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved PapersStudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsGeek on the TopCareersInternship
Practice DS & Algo.Must Do QuestionsDSA Topic-wiseDSA Company-wise
Must Do Questions
DSA Topic-wise
DSA Company-wise
AlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll Algorithms
Analysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity Question
Asymptotic Analysis
Worst, Average and Best Cases
Asymptotic Notations
Little o and little omega notations
Lower and Upper Bound Theory
Analysis of Loops
Solving Recurrences
Amortized Analysis
What does 'Space Complexity' mean ?
Pseudo-polynomial Algorithms
Polynomial Time Approximation Scheme
A Time Complexity Question
Searching Algorithms
Sorting Algorithms
Graph Algorithms
Pattern Searching
Geometric Algorithms
Mathematical
Bitwise Algorithms
Randomized Algorithms
Greedy Algorithms
Dynamic Programming
Divide and Conquer
Backtracking
Branch and Bound
All Algorithms
Data StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data Structures
Arrays
Linked List
Stack
Queue
Binary Tree
Binary Search Tree
Heap
Hashing
Graph
Advanced Data Structure
Matrix
Strings
All Data Structures
Interview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice Quizzes
Company Preparation
Top Topics
Practice Company Questions
Interview Experiences
Experienced Interviews
Internship Interviews
Competititve Programming
Design Patterns
System Design Tutorial
Multiple Choice Quizzes
LanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlin
C
C++
Java
Python
C#
JavaScript
jQuery
SQL
PHP
Scala
Perl
Go Language
HTML
CSS
Kotlin
CS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware Engineering
Mathematics
Operating System
DBMS
Computer Networks
Computer Organization and Architecture
Theory of Computation
Compiler Design
Digital Logic
Software Engineering
GATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CS
GATE Computer Science Notes
Last Minute Notes
GATE CS Solved Papers
GATE CS Original Papers and Official Keys
GATE 2021 Dates
GATE CS 2021 Syllabus
Important Topics for GATE CS
Web TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHP
HTML
CSS
JavaScript
AngularJS
ReactJS
NodeJS
Bootstrap
jQuery
PHP
Software DesignsSoftware Design PatternsSystem Design Tutorial
Software Design Patterns
System Design Tutorial
School LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes
School Programming
MathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculus
Number System
Algebra
Trigonometry
Statistics
Probability
Geometry
Mensuration
Calculus
Maths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 Notes
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
Class 12 Notes
NCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
RD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
Physics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
CS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers
ISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer Exam
ISRO CS Original Papers and Official Keys
ISRO CS Solved Papers
ISRO CS Syllabus for Scientist/Engineer Exam
UGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers
UGC NET CS Notes Paper II
UGC NET CS Notes Paper III
UGC NET CS Solved Papers
StudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsGeek on the TopCareersInternship
Campus Ambassador Program
School Ambassador Program
Project
Geek of the Month
Campus Geek of the Month
Placement Course
Competititve Programming
Testimonials
Geek on the Top
Careers
Internship
JobsApply for JobsPost a JobJOB-A-THON
Apply for Jobs
Post a Job
JOB-A-THON
Events




WriteCome write articles for us and get featuredPracticeLearn and code with the best industry expertsPremiumGet access to ad-free content, doubt assistance and more!JobsCome and find your dream job with usGeeks DigestQuizzesGeeks CampusGblog ArticlesIDECampus Mantri
Geeks Digest
Quizzes
Geeks Campus
Gblog Articles
IDE
Campus Mantri
Sign In
Sign In
Home
Saved Videos
Courses


For Working Professionals
                        



LIVE
                        


DSA Live Classes

System Design

Java Backend Development

Full Stack LIVE

Explore More


Self-Paced
                        


DSA- Self Paced

SDE Theory

Must-Do Coding Questions

Explore More


For Students
                        



LIVE
                        


Competitive Programming

Data Structures with C++

Data Science

Explore More


Self-Paced
                        


DSA- Self Paced

CIP

JAVA / Python / C++

Explore More


School Courses
                        


School Guide

Python Programming

Learn To Make Apps


Practice DS & Algo.
                        


Must Do Questions

DSA Topic-wise

DSA Company-wise


Algorithms
                        


Searching Algorithms

Sorting Algorithms

Graph Algorithms

Pattern Searching

Geometric Algorithms

Mathematical

Bitwise Algorithms

Randomized Algorithms

Greedy Algorithms

Dynamic Programming

Divide and Conquer

Backtracking

Branch and Bound

All Algorithms


Analysis of Algorithms
                        


Asymptotic Analysis

Worst, Average and Best Cases

Asymptotic Notations

Little o and little omega notations

Lower and Upper Bound Theory

Analysis of Loops

Solving Recurrences

Amortized Analysis

What does 'Space Complexity' mean ?

Pseudo-polynomial Algorithms

Polynomial Time Approximation Scheme

A Time Complexity Question


Data Structures
                        


Arrays

Linked List

Stack

Queue

Binary Tree

Binary Search Tree

Heap

Hashing

Graph

Advanced Data Structure

Matrix

Strings

All Data Structures


Interview Corner
                        


Company Preparation

Top Topics

Practice Company Questions

Interview Experiences

Experienced Interviews

Internship Interviews

Competititve Programming

Design Patterns

System Design Tutorial

Multiple Choice Quizzes


Languages
                        


C

C++

Java

Python

C#

JavaScript

jQuery

SQL

PHP

Scala

Perl

Go Language

HTML

CSS

Kotlin


CS Subjects
                        


Mathematics

Operating System

DBMS

Computer Networks

Computer Organization and Architecture

Theory of Computation

Compiler Design

Digital Logic

Software Engineering


GATE
                        


GATE Computer Science Notes

Last Minute Notes

GATE CS Solved Papers

GATE CS Original Papers and Official Keys

GATE 2021 Dates

GATE CS 2021 Syllabus

Important Topics for GATE CS


Web Technologies
                        


HTML

CSS

JavaScript

AngularJS

ReactJS

NodeJS

Bootstrap

jQuery

PHP


Software Designs
                        


Software Design Patterns

System Design Tutorial


School Learning
                        


School Programming


Mathematics
                        


Number System

Algebra

Trigonometry

Statistics

Probability

Geometry

Mensuration

Calculus


Maths Notes (Class 8-12)
                        


Class 8 Notes

Class 9 Notes

Class 10 Notes

Class 11 Notes

Class 12 Notes


NCERT Solutions
                        


Class 8 Maths Solution

Class 9 Maths Solution

Class 10 Maths Solution

Class 11 Maths Solution

Class 12 Maths Solution


RD Sharma Solutions
                        


Class 8 Maths Solution

Class 9 Maths Solution

Class 10 Maths Solution

Class 11 Maths Solution

Class 12 Maths Solution


Physics Notes (Class 8-11)
                        


Class 8 Notes

Class 9 Notes

Class 10 Notes

Class 11 Notes


CS Exams/PSUs
                        



ISRO
                        


ISRO CS Original Papers and Official Keys

ISRO CS Solved Papers

ISRO CS Syllabus for Scientist/Engineer Exam


UGC NET
                        


UGC NET CS Notes Paper II

UGC NET CS Notes Paper III

UGC NET CS Solved Papers


Student
                        


Campus Ambassador Program

School Ambassador Program

Project

Geek of the Month

Campus Geek of the Month

Placement Course

Competititve Programming

Testimonials

Geek on the Top

Careers

Internship


Tutorials
                        



Jobs
                        


Apply for Jobs

Post a Job

JOB-A-THON


For Working Professionals
                        



LIVE
                        


DSA Live Classes

System Design

Java Backend Development

Full Stack LIVE

Explore More


DSA Live Classes


System Design


Java Backend Development


Full Stack LIVE


Explore More


Self-Paced
                        


DSA- Self Paced

SDE Theory

Must-Do Coding Questions

Explore More


DSA- Self Paced


SDE Theory


Must-Do Coding Questions


Explore More


For Students
                        



LIVE
                        


Competitive Programming

Data Structures with C++

Data Science

Explore More


Competitive Programming


Data Structures with C++


Data Science


Explore More


Self-Paced
                        


DSA- Self Paced

CIP

JAVA / Python / C++

Explore More


DSA- Self Paced


CIP


JAVA / Python / C++


Explore More


School Courses
                        


School Guide

Python Programming

Learn To Make Apps


School Guide


Python Programming


Learn To Make Apps


Practice DS & Algo.
                        


Must Do Questions

DSA Topic-wise

DSA Company-wise


Must Do Questions


DSA Topic-wise


DSA Company-wise


Algorithms
                        


Searching Algorithms

Sorting Algorithms

Graph Algorithms

Pattern Searching

Geometric Algorithms

Mathematical

Bitwise Algorithms

Randomized Algorithms

Greedy Algorithms

Dynamic Programming

Divide and Conquer

Backtracking

Branch and Bound

All Algorithms


Searching Algorithms


Sorting Algorithms


Graph Algorithms


Pattern Searching


Geometric Algorithms


Mathematical


Bitwise Algorithms


Randomized Algorithms


Greedy Algorithms


Dynamic Programming


Divide and Conquer


Backtracking


Branch and Bound


All Algorithms


Analysis of Algorithms
                        


Asymptotic Analysis

Worst, Average and Best Cases

Asymptotic Notations

Little o and little omega notations

Lower and Upper Bound Theory

Analysis of Loops

Solving Recurrences

Amortized Analysis

What does 'Space Complexity' mean ?

Pseudo-polynomial Algorithms

Polynomial Time Approximation Scheme

A Time Complexity Question


Asymptotic Analysis


Worst, Average and Best Cases


Asymptotic Notations


Little o and little omega notations


Lower and Upper Bound Theory


Analysis of Loops


Solving Recurrences


Amortized Analysis


What does 'Space Complexity' mean ?


Pseudo-polynomial Algorithms


Polynomial Time Approximation Scheme


A Time Complexity Question


Data Structures
                        


Arrays

Linked List

Stack

Queue

Binary Tree

Binary Search Tree

Heap

Hashing

Graph

Advanced Data Structure

Matrix

Strings

All Data Structures


Arrays


Linked List


Stack


Queue


Binary Tree


Binary Search Tree


Heap


Hashing


Graph


Advanced Data Structure


Matrix


Strings


All Data Structures


Interview Corner
                        


Company Preparation

Top Topics

Practice Company Questions

Interview Experiences

Experienced Interviews

Internship Interviews

Competititve Programming

Design Patterns

System Design Tutorial

Multiple Choice Quizzes


Company Preparation


Top Topics


Practice Company Questions


Interview Experiences


Experienced Interviews


Internship Interviews


Competititve Programming


Design Patterns


System Design Tutorial


Multiple Choice Quizzes


Languages
                        


C

C++

Java

Python

C#

JavaScript

jQuery

SQL

PHP

Scala

Perl

Go Language

HTML

CSS

Kotlin


C


C++


Java


Python


C#


JavaScript


jQuery


SQL


PHP


Scala


Perl


Go Language


HTML


CSS


Kotlin


CS Subjects
                        


Mathematics

Operating System

DBMS

Computer Networks

Computer Organization and Architecture

Theory of Computation

Compiler Design

Digital Logic

Software Engineering


Mathematics


Operating System


DBMS


Computer Networks


Computer Organization and Architecture


Theory of Computation


Compiler Design


Digital Logic


Software Engineering


GATE
                        


GATE Computer Science Notes

Last Minute Notes

GATE CS Solved Papers

GATE CS Original Papers and Official Keys

GATE 2021 Dates

GATE CS 2021 Syllabus

Important Topics for GATE CS


GATE Computer Science Notes


Last Minute Notes


GATE CS Solved Papers


GATE CS Original Papers and Official Keys


GATE 2021 Dates


GATE CS 2021 Syllabus


Important Topics for GATE CS


Web Technologies
                        


HTML

CSS

JavaScript

AngularJS

ReactJS

NodeJS

Bootstrap

jQuery

PHP


HTML


CSS


JavaScript


AngularJS


ReactJS


NodeJS


Bootstrap


jQuery


PHP


Software Designs
                        


Software Design Patterns

System Design Tutorial


Software Design Patterns


System Design Tutorial


School Learning
                        


School Programming


School Programming


Mathematics
                        


Number System

Algebra

Trigonometry

Statistics

Probability

Geometry

Mensuration

Calculus


Number System


Algebra


Trigonometry


Statistics


Probability


Geometry


Mensuration


Calculus


Maths Notes (Class 8-12)
                        


Class 8 Notes

Class 9 Notes

Class 10 Notes

Class 11 Notes

Class 12 Notes


Class 8 Notes


Class 9 Notes


Class 10 Notes


Class 11 Notes


Class 12 Notes


NCERT Solutions
                        


Class 8 Maths Solution

Class 9 Maths Solution

Class 10 Maths Solution

Class 11 Maths Solution

Class 12 Maths Solution


Class 8 Maths Solution


Class 9 Maths Solution


Class 10 Maths Solution


Class 11 Maths Solution


Class 12 Maths Solution


RD Sharma Solutions
                        


Class 8 Maths Solution

Class 9 Maths Solution

Class 10 Maths Solution

Class 11 Maths Solution

Class 12 Maths Solution


Class 8 Maths Solution


Class 9 Maths Solution


Class 10 Maths Solution


Class 11 Maths Solution


Class 12 Maths Solution


Physics Notes (Class 8-11)
                        


Class 8 Notes

Class 9 Notes

Class 10 Notes

Class 11 Notes


Class 8 Notes


Class 9 Notes


Class 10 Notes


Class 11 Notes


CS Exams/PSUs
                        



ISRO
                        


ISRO CS Original Papers and Official Keys

ISRO CS Solved Papers

ISRO CS Syllabus for Scientist/Engineer Exam


ISRO CS Original Papers and Official Keys


ISRO CS Solved Papers


ISRO CS Syllabus for Scientist/Engineer Exam


UGC NET
                        


UGC NET CS Notes Paper II

UGC NET CS Notes Paper III

UGC NET CS Solved Papers


UGC NET CS Notes Paper II


UGC NET CS Notes Paper III


UGC NET CS Solved Papers


Student
                        


Campus Ambassador Program

School Ambassador Program

Project

Geek of the Month

Campus Geek of the Month

Placement Course

Competititve Programming

Testimonials

Geek on the Top

Careers

Internship


Campus Ambassador Program


School Ambassador Program


Project


Geek of the Month


Campus Geek of the Month


Placement Course


Competititve Programming


Testimonials


Geek on the Top


Careers


Internship


Tutorials
                        



Jobs
                        


Apply for Jobs

Post a Job

JOB-A-THON


Apply for Jobs


Post a Job


JOB-A-THON

GBlog
Puzzles
What's New ?
Array
Matrix
Strings
Hashing
Linked List
Stack
Queue
Binary Tree
Binary Search Tree
Heap
Graph
Searching
Sorting
Divide & Conquer
Mathematical
Geometric
Bitwise
Greedy
Backtracking
Branch and Bound
Dynamic Programming
Pattern Searching
Randomized
Primality Test | Set 2 (Fermat Method)
Primality Test | Set 3 (Miller–Rabin)
Primality Test | Set 4 (Solovay-Strassen)
Prime Numbers
Primality Test | Set 1 (Introduction and School Method)
Write an iterative O(Log y) function for pow(x, y)
Write a program to calculate pow(x,n)
Modular Exponentiation (Power in Modular Arithmetic)
Modular exponentiation (Recursive)
Modular multiplicative inverse
Euclidean algorithms (Basic and Extended)
Program to find GCD or HCF of two numbers
Program to find LCM of two numbers
LCM of given array elements
Finding LCM of more than two (or array) numbers without using GCD
GCD of more than two (or array) numbers
Sieve of Eratosthenes
Sieve of Eratosthenes in 0(n) time complexity
How is the time complexity of Sieve of Eratosthenes is n*log(log(n))?
Segmented Sieve
Segmented Sieve (Print Primes in a Range)
Prime Factorization using Sieve O(log n) for multiple queries
Efficient program to print all prime factors of a given number
Prime Factor
Pollard’s Rho Algorithm for Prime Factorization
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7
Primality Test | Set 2 (Fermat Method)
Primality Test | Set 3 (Miller–Rabin)
Primality Test | Set 4 (Solovay-Strassen)
Prime Numbers
Primality Test | Set 1 (Introduction and School Method)
Write an iterative O(Log y) function for pow(x, y)
Write a program to calculate pow(x,n)
Modular Exponentiation (Power in Modular Arithmetic)
Modular exponentiation (Recursive)
Modular multiplicative inverse
Euclidean algorithms (Basic and Extended)
Program to find GCD or HCF of two numbers
Program to find LCM of two numbers
LCM of given array elements
Finding LCM of more than two (or array) numbers without using GCD
GCD of more than two (or array) numbers
Sieve of Eratosthenes
Sieve of Eratosthenes in 0(n) time complexity
How is the time complexity of Sieve of Eratosthenes is n*log(log(n))?
Segmented Sieve
Segmented Sieve (Print Primes in a Range)
Prime Factorization using Sieve O(log n) for multiple queries
Efficient program to print all prime factors of a given number
Prime Factor
Pollard’s Rho Algorithm for Prime Factorization
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7
Difficulty Level :
Easy
A prime number is a natural number greater than 1, which is only divisible by 1 and itself. First few prime numbers are : 2 3 5 7 11 13 17 19 23 .....
Some interesting fact about Prime numbers 
Two is the only even Prime number.
Every prime number can be represented in form of 6n+1 or 6n-1 except the prime number 2 and 3, where n is a natural number.
Two and Three are only two consecutive natural numbers that are prime.
Goldbach Conjecture: Every even integer greater than 2 can be expressed as the sum of two primes.
Wilson Theorem: Wilson’s theorem states that a natural number p > 1 is a prime number if and only if
(p - 1) ! ≡  -1   mod p 
OR  (p - 1) ! ≡  (p-1) mod p
Fermat’s Little Theorem: If n is a prime number, then for every a, 1 <= a < n,
an-1 ≡ 1 (mod n)
OR 
an-1 % n = 1
Prime Number Theorem: The probability that a given, randomly chosen number n is prime is inversely proportional to its number of digits, or to the logarithm of n.
Lemoine’s Conjecture: Any odd integer greater than 5 can be expressed as a sum of an odd prime (all primes other than 2 are odd) and an even semiprime. A semiprime number is a product of two prime numbers. This is called Lemoine’s conjecture.
How we check whether a number is Prime or not? 
Naive solution. A naive solution is to iterate through all numbers from 2 to sqrt(n) and for every number check if it divides n. If we find any number that divides, we return false.
C++14
Java
Python3
C#
PHP
Javascript
// A school method based C++ program to// check if a number is prime#include <bits/stdc++.h>using namespace std; // function check whether a number// is prime or notbool isPrime(int n){    // Corner case    if (n <= 1)        return false;     // Check from 2 to square root of n    for (int i = 2; i <= sqrt(n); i++)        if (n % i == 0)            return false;     return true;} // Driver Codeint main(){    isPrime(11) ? cout << " true\n" : cout << " false\n";    return 0;}
// A school method based Java program to// check if a number is primeimport java.util.*;import java.lang.*; class GFG {     // Check for number prime or not    static boolean isPrime(int n)    {         // Check if number is less than        // equal to 1        if (n <= 1)            return false;         // Check if number is 2        else if (n == 2)            return true;         // Check if n is a multiple of 2        else if (n % 2 == 0)            return false;         // If not, then just check the odds        for (int i = 3; i <= Math.sqrt(n); i += 2)        {            if (n % i == 0)                return false;        }        return true;    }     // Driver code    public static void main(String[] args)    {        if (isPrime(19))            System.out.println("true");         else            System.out.println("false");    }} // This code is contributed by Ronak Bhensdadia
# A school method based Python3 program# to check if a number is prime # function check whether a number# is prime or not #import sqrt from math modulefrom math import sqrt def isPrime(n):     # Corner case    if (n <= 1):        return False     # Check from 2 to sqrt(n)    for i in range(2, int(sqrt(n))+1):        if (n % i == 0):            return False     return True  # Driver Codeif isPrime(11):    print("true")else:    print("false") # This code is contributed by Sachin Bisht
// A school method based C# program to// check if a number is primeusing System; class GFG {    // function check whether a    // number is prime or not    static bool isPrime(int n)    {        // Corner case        if (n <= 1)            return false;         // Check from 2 to sqrt(n)        for (int i = 2; i < Math.Sqrt(n); i++)            if (n % i == 0)                return false;         return true;    }     // Driver Code    static void Main()    {        if (isPrime(11))            Console.Write(" true");         else            Console.Write(" false");    }} // This code is contributed by Sam007
<?php// A school method based PHP program to// check if a number is prime // function check whether a number// is prime or notfunction isPrime($n){    // Corner case    if ($n <= 1)        return false;     // Check from 2 to n-1    for ($i = 2; $i < $n; $i++)        if ($n % $i == 0)            return false;     return true;} // Driver Codeif(isPrime(11))    echo("true");else    echo("false"); // This code is contributed by Ajit.?>
<script> // A school method based Javascript program to// check if a number is prime   // function check whether a number// is prime or notfunction isPrime(n){    // Corner case    if (n <= 1)        return false;      // Check from 2 to n-1    for (let i = 2; i < n; i++)        if (n % i == 0)            return false;      return true;}  // Driver Code     isPrime(11) ? document.write(" true" + "<br>") : document.write(" false" + "<br>"); // This code is contributed by Mayank Tyagi </script>
 true
Time Complexity: O() 
Using Recursion :
Recursion can also be used to check if a number between 2 to n – 1 divides n. If we find any number that divides, we return false.
C++
Java
Python3
C#
Javascript
// C++ program to check whether a number// is prime or not using recursion#include <iostream>using namespace std; // function check whether a number// is prime or notbool isPrime(int n){    static int i = 2;     // corner cases    if (n == 0 || n == 1) {        return false;    }     // Checking Prime    if (n == i)        return true;     // base cases    if (n % i == 0) {        return false;    }    i++;    return isPrime(n);} // Driver Codeint main(){     isPrime(35) ? cout << " true\n" : cout << " false\n";    return 0;} // This code is contributed by yashbeersingh42
// Java program to check whether a number// is prime or not using recursionclass GFG{     static int i = 2;  // Function check whether a number// is prime or notpublic static boolean isPrime(int n){         // Corner cases    if (n == 0 || n == 1)    {        return false;    }       // Checking Prime    if (n == i)        return true;             // Base cases    if (n % i == 0)    {        return false;    }    i++;    return isPrime(n);} // Driver Code  public static void main(String[] args){    if (isPrime(35))    {        System.out.println("true");    }    else    {        System.out.println("false");    }}} // This code is contributed by divyeshrabadiya07
# Python3 program to check whether a number# is prime or not using recursion # Function check whether a number# is prime or notdef isPrime(n, i):         # Corner cases    if (n == 0 or n == 1):        return False         # Checking Prime     if (n == i):        return True         # Base cases    if (n % i == 0):        return False         i += 1         return isPrime(n, i) # Driver Codeif (isPrime(35, 2)):  print("true")else:  print("false")   #  This code is contributed by bunnyram19
// C# program to check whether a number// is prime or not using recursionusing System;class GFG {         static int i = 2;         // function check whether a number    // is prime or not    static bool isPrime(int n)    {              // corner cases        if (n == 0 || n == 1) {            return false;        }              // Checking Prime        if (n == i)            return true;              // base cases        if (n % i == 0) {            return false;        }        i++;        return isPrime(n);    }     static void Main() {    if(isPrime(35))    {        Console.WriteLine("true");    }    else{        Console.WriteLine("false");    }  }} // This code is contributed by divyesh072019
<script>      // JavaScript program to check whether a number      // is prime or not using recursion       // function check whether a number      // is prime or not      function isPrime(n) {        var i = 1;         // corner cases        if (n == 0 || n == 1) {          return false;        }         // Checking Prime        if (n == i) return true;         // base cases        if (n % i == 0) {          return false;        }        i++;        return isPrime(n);      }       // Driver Code       isPrime(35) ? document.write(" true\n") : document.write(" false\n");             // This code is contributed by rdtank.    </script>
 false
Time Complexity :O(N), Space Complexity :O(N) 
Efficient solutions Primality Test | Set 1 (Introduction and School Method)Primality Test | Set 2 (Fermat Method)Primality Test | Set 3 (Miller–Rabin)Primality Test | Set 4 (Solovay-Strassen)Lucas Primality Test
Primality Test | Set 1 (Introduction and School Method)
Primality Test | Set 2 (Fermat Method)
Primality Test | Set 3 (Miller–Rabin)
Primality Test | Set 4 (Solovay-Strassen)
Lucas Primality Test
Algorithms to find all prime numbers smaller than the N. 
Sieve of Eratosthenes
Sieve of Eratosthenes in 0(n) time complexity
Segmented Sieve
Sieve of Sundaram
Bitwise Sieve
Recent Articles on Sieve!
More problems related to Prime number 
Find two distinct prime numbers with a given product
Print all prime numbers less than or equal to N
Recursive program for prime number
Find two prime numbers with a given sum
Find the highest occurring digit in prime numbers in a range
Prime Factorization using Sieve O(log n) for multiple queries
Program to print all prime factors of a given number
Least prime factor of numbers till n
Prime factors of LCM of array elements – GeeksforGeeks
Program for Goldbach’s Conjecture
Prime numbers and Fibonacci
Composite Number
Recent Articles on Prime Numbers!
jit_t
gaurav1903arora
ronakbhensdadia
shubhamr238
yashbeersingh42
wwwsidharth56
divyesh072019
divyeshrabadiya07
bunnyram19
kunal530
mayanktyagi1709
rdtank
pritammajumder
amansharma14
surinderdawra388
akshaymulky5211
jai00271
Prime Number
series
sieve
Mathematical
Mathematical
Prime Number
series
sieve
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Program for Decimal to Binary Conversion
Find all factors of a natural number | Set 1
Program to find sum of elements in a given array
Modulo 10^9+7 (1000000007)
The Knight's tour problem | Backtracking-1
Program for factorial of a number
Operators in C / C++
Minimum number of jumps to reach end