Learn Python interactively.
Learn Python practically and Get Certified .

Popular Tutorials
Popular examples, reference materials.
Learn Python Interactively
Python Examples
Check if a Number is Positive, Negative or 0
- Check if a Number is Odd or Even
- Check Leap Year
- Find the Largest Among Three Numbers
- Check Prime Number
Print all Prime Numbers in an Interval
Find the Factorial of a Number
- Display the multiplication Table
Related Topics
- Python while Loop
- Python range()
- Python break and continue
- Python for Loop
- Python if...else Statement
- Python Looping Techniques
Python Program to Check Prime Number
Example to check whether an integer is a prime number or not using for loop and if...else statement. If the number is not prime, it's explained in output why it is not a prime number.
To understand this example, you should have the knowledge of the following Python programming topics:
A positive integer greater than 1 which has no other factors except 1 and the number itself is called a prime number. 2, 3, 5, 7 etc. are prime numbers as they do not have any other factors. But 6 is not prime (it is composite) since, 2 x 3 = 6 .
Example 1: Using a flag variable
In this program, we have checked if num is prime or not. Numbers less than or equal to 1 are not prime numbers. Hence, we only proceed if the num is greater than 1.
We check if num is exactly divisible by any number from 2 to num - 1 . If we find a factor in that range, the number is not prime, so we set flag to True and break out of the loop.
Outside the loop, we check if flag is True or False .
- If it is True , num is not a prime number.
- If it is False , num is a prime number.
Note : We can improve our program by decreasing the range of numbers where we look for factors.
In the above program, our search range is from 2 to num - 1 .
We could have used the range, range(2,num//2) or range(2,math.floor(math.sqrt(num)+1)) . The latter range is based on the fact that a composite number must have a factor less than or equal to the square root of that number. Otherwise, the number is prime.
You can change the value of variable num in the above source code to check whether a number is prime or not for other integers.
In Python, we can also use the for...else statement to do this task without using an additional flag variable.
Example 2: Using a for...else statement
Here, we have used a for..else statement to check if num is prime.
It works on the logic that the else clause of the for loop runs if and only if we don't break out the for loop. That condition is met only when no factors are found, which means that the given number is prime.
So, in the else clause, we print that the number is prime.
Sorry about that.
Related Examples
Python Example
Find the Factors of a Number
Try PRO for FREE
- Data Structure & Algorithm Classes (Live)
- System Design (Live)
- DevOps(Live)
- Explore More Live Courses
- Interview Preparation Course
- Data Science (Live)
GATE CS & IT 2024
- Data Structure & Algorithm-Self Paced(C++/JAVA)
- Data Structures & Algorithms in Python
- Explore More Self-Paced Courses
- C++ Programming - Beginner to Advanced
- Java Programming - Beginner to Advanced
- C Programming - Beginner to Advanced
- Full Stack Development with React & Node JS(Live)
- Java Backend Development(Live)
- Android App Development with Kotlin(Live)
- Python Backend Development with Django(Live)
- Complete Data Science Program(Live)
Mastering Data Analytics
- DevOps Engineering - Planning to Production
- CBSE Class 12 Computer Science
- School Guide
- All Courses
- Linked List
- Binary Tree
- Binary Search Tree
- Advanced Data Structure
- All Data Structures
- 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
- Company Preparation
- Practice Company Questions
- Interview Experiences
- Experienced Interviews
- Internship Interviews
- Competitive Programming
- Design Patterns
- System Design Tutorial
- Multiple Choice Quizzes
- Go Language
- Tailwind CSS
- Foundation CSS
- Materialize CSS
- Semantic UI
- Angular PrimeNG
- Angular ngx Bootstrap
- jQuery Mobile
- jQuery EasyUI
- React Bootstrap
- React Rebass
- React Desktop
- React Suite
- ReactJS Evergreen
- ReactJS Reactstrap
- BlueprintJS
- TensorFlow.js
- English Grammar
- School Programming
- Number System
- Trigonometry
- Probability
- Mensuration
- Class 8 Syllabus
- Class 9 Syllabus
- Class 10 Syllabus
- Class 11 Syllabus
- Class 8 Notes
- Class 9 Notes
- Class 10 Notes
- Class 11 Notes
- Class 12 Notes
- Class 8 Formulas
- Class 9 Formulas
- Class 10 Formulas
- Class 11 Formulas
- Class 8 Maths Solution
- Class 9 Maths Solution
- Class 10 Maths Solution
- Class 11 Maths Solution
- Class 12 Maths Solution
- Class 7 Notes
- History Class 7
- History Class 8
- History Class 9
- Geo. Class 7
- Geo. Class 8
- Geo. Class 9
- Civics Class 7
- Civics Class 8
- Business Studies (Class 11th)
- Microeconomics (Class 11th)
- Statistics for Economics (Class 11th)
- Business Studies (Class 12th)
- Accountancy (Class 12th)
- Macroeconomics (Class 12th)
- Machine Learning
- Data Science
- Mathematics
- Operating System
- Computer Networks
- Computer Organization and Architecture
- Theory of Computation
- Compiler Design
- Digital Logic
- Software Engineering
- GATE 2024 Live Course
- GATE Computer Science Notes
- Last Minute Notes
- GATE CS Solved Papers
- GATE CS Original Papers and Official Keys
- GATE CS 2023 Syllabus
- Important Topics for GATE CS
- GATE 2023 Important Dates
- Software Design Patterns
- HTML Cheat Sheet
- CSS Cheat Sheet
- Bootstrap Cheat Sheet
- JS Cheat Sheet
- jQuery Cheat Sheet
- Angular Cheat Sheet
- Facebook SDE Sheet
- Amazon SDE Sheet
- Apple SDE Sheet
- Netflix SDE Sheet
- Google SDE Sheet
- Wipro Coding Sheet
- Infosys Coding Sheet
- TCS Coding Sheet
- Cognizant Coding Sheet
- HCL Coding Sheet
- FAANG Coding Sheet
- Love Babbar Sheet
- Mass Recruiter Sheet
- Product-Based Coding Sheet
- Company-Wise Preparation Sheet
- Array Sheet
- String Sheet
- Graph Sheet
- ISRO CS Original Papers and Official Keys
- ISRO CS Solved Papers
- ISRO CS Syllabus for Scientist/Engineer Exam
- UGC NET CS Notes Paper II
- UGC NET CS Notes Paper III
- UGC NET CS Solved Papers
- Campus Ambassador Program
- School Ambassador Program
- Geek of the Month
- Campus Geek of the Month
- Placement Course
- Testimonials
- Student Chapter
- Geek on the Top
- Geography Notes
- History Notes
- Science & Tech. Notes
- Ethics Notes
- Polity Notes
- Economics Notes
- UPSC Previous Year Papers
- SSC CGL Syllabus
- General Studies
- Subjectwise Practice Papers
- Previous Year Papers
- SBI Clerk Syllabus
- General Awareness
- Quantitative Aptitude
- Reasoning Ability
- SBI Clerk Practice Papers
- SBI PO Syllabus
- SBI PO Practice Papers
- IBPS PO 2022 Syllabus
- English Notes
- Reasoning Notes
- Mock Question Papers
- IBPS Clerk Syllabus
- Apply for a Job
- Apply through Jobathon
- Hire through Jobathon
- All DSA Problems
- Problem of the Day
- GFG SDE Sheet
- Top 50 Array Problems
- Top 50 String Problems
- Top 50 Tree Problems
- Top 50 Graph Problems
- Top 50 DP Problems
- Solving For India-Hackthon
- GFG Weekly Coding Contest
- Job-A-Thon: Hiring Challenge
- BiWizard School Contest
- All Contests and Events
- Saved Videos
- What's New ?
- Divide & Conquer
Related Articles
- Write Articles
- Pick Topics to write
- Guidelines to Write
- Get Technical Writing Internship
- Write an Interview Experience
- Mathematical Algorithms
- Check if a large number is divisible by 3 or not
- Check if a large number is divisible by 4 or not
- Check if a large number is divisible by 6 or not
- Check divisibility by 7
- Check if a large number is divisible by 9 or not
- Check if a large number is divisible by 11 or not
- Divisibility by 12 for a large number
- Check if a large number is divisible by 13 or not
- Check if a large number is divisibility by 15
- Number is divisible by 29 or not
- LCM of given array elements
- GCD of more than two (or array) numbers
- Euclidean algorithms (Basic and Extended)
- Stein’s Algorithm for finding GCD
- GCD, LCM and Distributive Property
- Count number of pairs (A <= N, B <= N) such that gcd (A , B) is B
- Program to find GCD of floating point numbers
- Series with largest GCD and sum equals to n
- Largest Subset with GCD 1
- Summation of GCD of all the pairs up to N
- Juggler Sequence
- Padovan Sequence
- Aliquot Sequence
- Moser-de Bruijn Sequence
- Stern-Brocot Sequence
- Newman-Conway Sequence
- Sylvester’s sequence
- Recaman’s sequence
- Sum of the sequence 2, 22, 222, ………
- Sum of series 1^2 + 3^2 + 5^2 + . . . + (2*n – 1)^2
- Sum of the series 0.6, 0.06, 0.006, 0.0006, …to n terms
- n-th term in series 2, 12, 36, 80, 150….
- Minimum digits to remove to make a number Perfect Square
- Print first k digits of 1/n where n is a positive integer
- Check if a given number can be represented in given a no. of digits in any base
- Find element using minimum segments in Seven Segment Display
- Find next greater number with same set of digits
- Check if a number is jumbled or not
- Numbers having difference with digit sum more than s
- Total numbers with no repeated digits in a range
- K-th digit in ‘a’ raised to power ‘b’
- Program to add two polynomials
- Multiply two polynomials
- Find number of solutions of a linear equation of n variables
- Calculate the Discriminant Value
- Program for dot product and cross product of two vectors
- Iterated Logarithm log*(n)
- Program to find correlation coefficient
- Program for Muller Method
- Number of non-negative integral solutions of a + b + c = n
- Generate Pythagorean Triplets
- Exponential notation of a decimal number
- Check if a number is power of k using base changing method
- Convert a binary number to hexadecimal number
- Program for decimal to hexadecimal conversion
- Converting a Real Number (between 0 and 1) to Binary String
- Convert from any base to decimal and vice versa
- Decimal to binary conversion without using arithmetic operators
Prime Numbers
- Left-Truncatable Prime
- Mersenne Prime
- Super Prime
- Hardy-Ramanujan Theorem
- Rosser’s Theorem
- Fermat’s little theorem
- Introduction to Primality Test and School Method
- Vantieghems Theorem for Primality Test
- AKS Primality Test
- Lucas Primality Test
- Efficient program to print all prime factors of a given number
- Smith Number
- Sphenic Number
- Hoax Number
- k-th prime factor of a given number
- Pollard’s Rho Algorithm for Prime Factorization
- Finding power of prime number p in n!
- Find all factors of a Natural Number
- Find numbers with n-divisors in a given range
- Modular Exponentiation (Power in Modular Arithmetic)
- Modular multiplicative inverse
- Modular Division
- Euler’s criterion (Check if square root under modulo p exists)
- Find sum of modulo K of first N natural number
- How to compute mod of a big number?
- Exponential Squaring (Fast Modulo Multiplication)
- Trick for modular division ( (x1 * x2 …. xn) / b ) mod (m)
- Program for factorial of a number
- Legendre’s formula (Given p and n, find the largest x such that p^x divides n!)
- Count trailing zeroes in factorial of a number
- Find the Factorial of a large number
- Primorial of a number
- Find maximum power of a number that divides a factorial
- Largest power of k in n! (factorial) where k may not be prime
- Check if a number is a Krishnamurthy Number or not
- Last non-zero digit of a factorial
- Count digits in a factorial using Logarithm
- Program for Fibonacci numbers
- Interesting facts about Fibonacci numbers
- Zeckendorf’s Theorem (Non-Neighbouring Fibonacci Representation)
- Find nth Fibonacci number using Golden ratio
- Matrix Exponentiation
- Fibonacci Coding
- Cassini’s Identity
- Tail Recursion for Fibonacci
- Program for nth Catalan Number
- Applications of Catalan Numbers
- Find the number of valid parentheses expressions of given length
- Binomial Coefficient | DP-9
- Introduction and Dynamic Programming solution to compute nCr%p
- Program to calculate value of nCr
- Rencontres Number (Counting partial derangements)
- Sum of squares of binomial coefficients
- Space and time efficient Binomial Coefficient
- Horner’s Method for Polynomial Evaluation
- Minimize the absolute difference of sum of two subsets
- Sum of all subsets of a set formed by first n natural numbers
- Sum of average of all subsets
- Bell Numbers (Number of ways to Partition a Set)
- Sieve of Eratosthenes
- Segmented Sieve
- Sieve of Atkin
- Sieve of Sundaram to print all primes smaller than n
- Sieve of Eratosthenes in 0(n) time complexity
- Prime Factorization using Sieve O(log n) for multiple queries
- Euler’s Totient Function
- Optimized Euler Totient Function for Multiple Evaluations
- Euler’s Totient function for all numbers smaller than or equal to n
- Primitive root of a prime number n modulo n
- Euler’s Four Square Identity
- Introduction to Chinese Remainder Theorem
- Implementation of Chinese Remainder theorem (Inverse Modulo based implementation)
- Cyclic Redundancy Check and Modulo-2 Division
- Using Chinese Remainder Theorem to Combine Modular equations
- Interquartile Range (IQR)
- Simulated Annealing
- Pseudo Random Number Generator (PRNG)
- Square root of a number using log
- Find ways an Integer can be expressed as sum of n-th power of unique natural numbers
- N-th root of a number
- Fast Fourier Transformation for polynomial multiplication
- Find Harmonic mean using Arithmetic mean and Geometric mean
- Double Base Palindrome
- Program for Derivative of a Polynomial
- Sgn value of a polynomial
- Check if a number is a power of another number
- Program to evaluate simple expressions
- Implement *, – and / operations using only + arithmetic operator
- Difficulty Level : Easy
- Discuss(20+)
What are prime numbers?
- 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…..
Prime numbers
- In other words, the prime number is a positive integer greater than 1 that has exactly two factors, 1 and the number itself.
- There are many prime numbers, such as 2, 3, 5, 7, 11, 13, etc.
- Keep in mind that 1 cannot be either prime or composite.
- The remaining numbers, except for 1, are classified as prime and composite numbers.
DSA Self Paced Course
Some interesting facts about Prime numbers:
- Except for 2, which is the smallest prime number and the only even prime number, all prime numbers are odd numbers.
- Every prime number can be represented in form of 6n + 1 or 6n – 1 except the prime numbers 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
- Fermat’s Little Theorem : If n is a prime number, then for every a, 1 <= a < n,
- 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.
Properties of prime numbers:
- Every number greater than 1 can be divided by at least one prime number.
- Every even positive integer greater than 2 can be expressed as the sum of two primes.
- Except 2, all other prime numbers are odd. In other words, we can say that 2 is the only even prime number.
- Two prime numbers are always coprime to each other.
- Each composite number can be factored into prime factors and individually all of these are unique in nature.
Prime numbers and co-prime numbers:
It is important to distinguish between prime numbers and co-prime numbers. Listed below are the differences between prime and co-prime numbers.
- A coprime number is always considered as a pair, whereas a prime number is considered as a single number.
- Co-prime numbers are numbers that have no common factor except 1. In contrast, prime numbers do not have such a condition.
- A co-prime number can be either prime or composite, but its greatest common factor (GCF) must always be 1. Unlike composite numbers, prime numbers have only two factors, 1 and the number itself.
- Example of co-prime: 13 and 15 are co-primes. The factors of 13 are 1 and 13 and the factors of 15 are 1, 3 and 5. We can see that they have only 1 as their common factor, therefore, they are coprime numbers.
- Example of prime: A few examples of prime numbers are 2, 3, 5, 7 and 11 etc.
How do we check whether a number is Prime or not?
Naive Approach: 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.
Below is the implementation:
Time Complexity: O(sqrt(n)) Auxiliary space: O(1)
Efficient approach: To check whether the number is prime or not follow the below idea:
In the previous approach given if the size of the given number is too large then its square root will be also very large, so to deal with large size input we will deal with a few numbers such as 1, 2, 3, and the numbers which are divisible by 2 and 3 in separate cases and for remaining numbers, we will iterate our loop from 5 to sqrt(n) and check for each iteration whether that (iteration) or (that iteration + 2) divides n or not. If we find any number that divides, we return false.
Below is the implementation for the above idea:
Time complexity: O(sqrt(n)) Auxiliary space: O(1)
Approach 3: To check the number is prime or not using recursion follow the below idea:
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.
Below is the implementation for the below idea:
Time Complexity: O(N) Auxiliary Space: O(N)
Approach 4: To check the number is prime or not using Fermat’s little theorem with out using loop
Time complexity: O(1) Auxiliary space: O(1)
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)
Algorithms to find all prime numbers smaller than the N.
- 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
- 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!
Solve DSA problems on GfG Practice.
Please Login to comment...
- gaurav1903arora
- ronakbhensdadia
- shubhamr238
- yashbeersingh42
- wwwsidharth56
- divyesh072019
- divyeshrabadiya07
- mayanktyagi1709
- pritammajumder
- amansharma14
- surinderdawra388
- akshayhmulky
- suruchikumarimfp4
- kashishkumar2
- simmytarika5
- abhijeet19403
- harendrakumar123
- shaikasif7616
- surajrasr7277
- vikramshirsath177
- susobhanakhuli
- Prime Number
Data Structures & Algorithms in Python - Self Paced
Complete interview preparation - self paced, complete test series for product-based companies, data structures and algorithms - self paced, complete test series for service-based companies, competitive programming - live, dsa live for working professionals - live, python programming foundation -self paced, system design - live, complete machine learning & data science program, improve your coding skills with practice, start your coding journey now.

- Design Pattern
- Interview Q
C Interview
- Send your Feedback to [email protected]
Help Others, Please Share

Learn Latest Tutorials

Transact-SQL

Reinforcement Learning

R Programming

React Native

Python Design Patterns

Python Pillow

Python Turtle

Preparation

Verbal Ability

Interview Questions

Company Questions
Trending Technologies

Artificial Intelligence

Cloud Computing

Data Science

Machine Learning

B.Tech / MCA

Data Structures

Operating System

Computer Network

Compiler Design

Computer Organization

Discrete Mathematics

Ethical Hacking

Computer Graphics

Software Engineering

Web Technology

Cyber Security

C Programming

Control System

Data Mining

Data Warehouse
Javatpoint Services
JavaTpoint offers too many high quality services. Mail us on [email protected] , to get more information about given services.
- Website Designing
- Website Development
- Java Development
- PHP Development
- Graphic Designing
- Digital Marketing
- On Page and Off Page SEO
- Content Development
- Corporate Training
- Classroom and Online Training
Training For College Campus
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected] Duration: 1 week to 2 week

C Program to Check whether the Given Number is a Prime
C programming examples tutorial index.
A prime number is a natural number that has only one and itself as factors.
Above numbers can only be divided evenly by 1 or itself , so these numbers are prime numbers.
Prime Number Check Program in C
1st iteration : i = 1; i <= 5; i++ here i is incremented i.e. i value for next iteration is 2 now if(n%i==0) then c is incremented i.e.if(5%1==0)then c is incremented, here 5%1=0 thus c is incremented. now c=1;
2nd iteration : i = 2; i <= 5; i++ here i is incremented i.e. i value for next iteration is 3 now if(n%i==0) then c is incremented i.e.if(5%2==0) then c is incremented, but 5%2!=0 and so c is not incremented, c remains 1 c=1;
4th iteration : i = 4; i <= 5; i++ here i is incremented i.e. i value for next iteration is 5 now if(n%i==0) then c is incremented i.e. if(5%4==0) then c is incremented, but 5%4!=0 and so c is not incremented, c remains 1 c=1;
- C program for prime number
C program example for prime number:
What is prime number?
A number is considered as prime number when it satisfies the below conditions.
- It should be whole number
- It should be greated than 1
- It should have only 2 factors. They are, 1 and the number itself.
Example for prime numbers: 2, 3, 5, 7, 11, 13, 17, 19, 23 etc.
Why 4, 6, 8, 9, 10, 12, 14, 15, 16 etc are not prime numbers?
Because, the number 4 can be factored as 2*2 and 1*4. As per the rule of prime number, there should be 2 factors only. They are 1 and the number itself. But, number 4 has 2*2 also. Like this, all remaining numbers 6, 8, 9, 10, 12, 14, 15, 16 have factors other than 1 and the number itself. So, these are not called as prime numbers.
Example C program for prime number:
Output of c program for prime number:, other c programs:.
- C program for factorial
- C program for fibonacci series
- C program for palindrome
- C program for swapping 2 numbers with and without temp variables
- C program to find leap year
- C program to find armstrong number
- C program to find simple and compound interest
- C program to find largest of given 3 numbers
- C program to find smallest of given 3 numbers
- C program to convert lower case into upper case and vice versa
- C program to find sum and average of given 3 numbers
- C program to sum up all individual digits
- C program to reverse given number
- C program to reverse given string
- C program to find strong number
- C program to find square and cube of given number
- C program to print hello world without using semi colon
- C program to sort given names in alphabetical order
- C program to copy content of one file to another
- C program to sort given numbers in ascending order
- C program to sort given numbers in descending order
- C program to search given number in an array
- C program for recursive function
- C program for calculator application
- C program for bank application
- C program to check given number is perfect number or not
- C program to find array size
- C program to find whether given character vowel or not
- C program to check whether given number is positive or negative
- C program to find sum of n numbers
- C program to compare 2 numbers without if statement
- C program to generate random numbers
- C program to compare 2 arrays whether they are equal or not
- C program to print number from 1 to 500 without using any loop conditions
- C program to insert an element into an array
- C program to delete an element from an array
- C program to find hcf (gcd) and lcm
- C program to print diamond pattern
- C program to print pascal triangle
- C program to add two complex numbers
- C program for matrix addition
- C program for matrix multiplication
- C program for bubble sort
- C program for insertion sort
- C program for selection sort
- Coding Ground
- Corporate Training

- Learn C By Examples Time
- Learn C by Examples - Home
- C Examples - Simple Programs
- C Examples - Loops/Iterations
- C Examples - Patterns
- C Examples - Arrays
- C Examples - Conversion
- C Examples - Strings
- C Examples - Mathematics
- C Examples - Linked List
- C Examples - File Handling
- C Programming Useful Resources
- Learn C By Examples - Quick Guide
- Learn C By Examples - Resources
- Learn C By Examples - Discussion
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
Prime Number Program In C
Any whole number which is greater than 1 and has only two factors that is 1 and the number itself, is called a prime number. Other than these two number it has no positive divisor. For example −
Few prime number are − 1, 2, 3, 5 , 7, 11 etc.
Algorithm of this program is very easy −
Flow Diagram
We can draw a flow diagram for this program as given below −

We can draft a pseudocode of the above algorithm as follows −
Implementation
Implementation of this algorithm is given below −
Output of the program should be −
Introduction to Python
- Learn Python Programming – One Stop Solution for Beginners

What is Python language? Is it easy to learn?
- Python Tutorial – Python Programming For Beginners
- Python: Interesting Facts You Need To Know
- Which are the best books for Python?
- Top 10 Features of Python You Need to Know
- Top 10 Python Applications in the Real World You Need to Know
- Python Anaconda Tutorial : Everything You Need To Know
Top 10 Reasons Why You Should Learn Python
- What are Important Advantages and Disadvantages Of Python?
- Python and Netflix: What Happens When You Stream a Film?
- How to Learn Python 3 from Scratch – A Beginners Guide
- Top 10 Best IDE for Python: How to choose the best Python IDE?
- How To Use Python For DevOps?
- Python vs C: Know what are the differences
- Python vs C++: Know what are the differences
- Ruby vs Python : What are the Differences?
Python Installation
- Install Python On Windows – Python 3.X Installation Guide
- How To Run Python In Ubuntu (Linux)?
- What is Python Spyder IDE and How to use it?
- How To Add Python to Path?
- Introduction to Atom Python Text Editor and how to configure it
- Python 101 : Hello World Program
Python Fundamentals
- Python Basics: What makes Python so Powerful?
- Data Structures You Need To Learn In Python
- What is the use of self in Python?
- Python Programming – Beginners Guide To Python Programming Language
- What is print in Python and How to use its Parameters?
- Important Python Data Types You Need to Know
- PyCharm Tutorial: Writing Python Code In PyCharm (IDE)
- Python Visual Studio- Learn How To Make Your First Python Program
- What is the Main Function in Python and how to use it?
- What is Try Except in Python and how it works?
- What are Comments in Python and how to use them?
- How to fetch and modify Date and Time in Python?
- Inheritance In Python With Examples: All You Need To Know
- How To Best Utilize Python CGI In Day To Day Coding?
- Python Constructors: Everything You Need To Know
- How To Create Your First Python Metaclass?
Init In Python: Everything You Need To Know
- Learn How To Use Split Function In Python
- How to Read CSV File in Python?
- Stack in Python: How, why and where?
- Hash Tables and Hashmaps in Python: What are they and How to implement?
- What is Random Number Generator in Python and how to use it?
- How to find Square Root in Python?
- Arrays in Python – What are Python Arrays and how to use them?
- Loops In Python: Why Should You Use One?
- What are Sets in Python and How to use them?
- What is Method Overloading in Python and How it Works?
- Python Functions : A Complete Beginners Guide
- Learn How To Use Map Function In Python With Examples
- Python time sleep() – One Stop Solution for time.sleep() Method
- How To Reverse A String In Python?
- How To Sort A Dictionary In Python : Sort By Keys , Sort By Values
- String Function In Python: How To Use It with Examples
- How To Convert Decimal To Binary In Python
- Python Tuple With Example: Everything You Need To Know
- How To Input a List in Python?
- How to Find Length of List in Python?
- How to Reverse a List in Python: Learn Python List Reverse() Method
- Learn What is Range in Python With Examples
- Everything You Need To Know About Hash In Python
- What Isinstance In Python And How To Implement It?
- How To Best Implement Armstrong Number In Python?
- How To Implement Round Function In Python?
- How To Implement 2-D arrays in Python?
Learn How To Make Python Pattern Programs With Examples
- Introduction To File Handling In Python
- What is Python JSON and How to implement it?
- Threading In Python: Learn How To Work With Threads In Python
- How To Best Implement Multiprocessing In Python?
- Know all About Robot Framework With Python
- What is Mutithreading in Python and How to Achieve it?
- Map, Filter and Reduce Functions in Python: All you need to know
- What is the Format Function in Python and How does it work?
- Python Database Connection: Know how to connect with database
- What are Lambda Functions and How to Use Them?
- What are Generators in Python and How to use them?
- Python Iterators: What is Iterator in Python and how to use it?
Python For Loop Tutorial With Examples To Practice
- While Loop In Python : All You Need To Know
- What is Socket Programming in Python and how to master it?
- Regular Expression in Python With Example
- How to Parse and Modify XML in Python?
Python OOPs
- Object Oriented Programming Python: All you need to know
- Python Class – Object Oriented Programming
- What is Polymorphism in OOPs programming?
- Python String Concatenation : Everything You Need To Know
- Everything You Need To Know About Print Exception In Python
Python Libraries
- Top 10 Python Libraries You Must Know In 2023
- How To Install NumPy In Python?
- Python NumPy Tutorial – Introduction To NumPy With Examples
- Python Pandas Tutorial : Learn Pandas for Data Analysis
- Python Matplotlib Tutorial – Data Visualizations In Python With Matplotlib
- Python Seaborn Tutorial: What is Seaborn and How to Use it?
- SciPy Tutorial: What is Python SciPy and How to use it?
- How To Make A Chatbot In Python?
- FIFA World Cup 2018 Best XI: Analyzing Fifa Dataset Using Python
- Scikit learn – Machine Learning using Python
- The Why And How Of Exploratory Data Analysis In Python
- OpenCV Python Tutorial: Computer Vision With OpenCV In Python
- Tkinter Tutorial For Beginners | GUI Programming Using Tkinter In Python
- Introduction To Game Building With Python's Turtle Module
- PyGame Tutorial – Game Development Using PyGame In Python
- PyTorch Tutorial – Implementing Deep Neural Networks Using PyTorch
- Scrapy Tutorial: How To Make A Web-Crawler Using Scrapy?
Web Scraping
- A Beginner's Guide to learn web scraping with python!
- Python Requests Module Tutorial – Sending HTTP Requests Using Requests Module
- Django Tutorial – Web Development with Python Django Framework
- Django vs Flask: Which is the best for your Web Application?
- Top 50 Django Interview Questions and Answers You Need to Know in 2023
Python Programs
- How to Check a Number is Palindrome in Python?
How to Find Prime Numbers in Python
- How To Implement GCD In Python?
- How To Convert Lists To Strings In Python?
- How to Display Fibonacci Series in Python?
- How to implement Python program to check Leap Year?
- How to reverse a number in Python?
- How to Implement a Linked List in Python?
- How to implement Bubble Sort in Python?
- How to implement Merge Sort in Python?
- A 101 Guide On The Least Squares Regression Method
Career Oppurtunities
Python career opportunities: your career guide to python programming.
- Top Python developer Skills you need to know
- Learn How To Make A Resume For A Python Developer
- What is the Average Python Developer Salary?
- How To Become A Python Developer : Learning Path For Python
- Why You Should Choose Python For Big Data
Interview Questions
Top 100+ python interview questions you must prepare in 2023.
- Top 50 OOPs Interview Questions and Answers in 2023
- Top Python Projects You Should Consider Learning
Data Science
A prime number is a natural number greater than 1 and it does not have any divisor other than 1 and itself. You can write a code in Python that will help you find all the prime numbers.
Python Full Course – Learn Python in 12 Hours | Python Tutorial For Beginners | Edureka
This Edureka Python Full Course helps you to became a master in basic and advanced Python Programming Concepts.
In this article, we will see how to write a prime number program in Python in the following sequence:
- What is a Prime number?
Optimized Method
Let’s get started.
What is a Prime Number?
A positive integer greater than 1 which does not have other factors except 1 and the number itself is called a prime number. The numbers 2, 3, 5, 7, etc. are prime numbers as they do not have any other factors. To find a prime number in Python, you have to iterate the value from start to end using a for loop and for every number, if it is greater than 1, check if it divides n. If we find any other number which divides, print that value.
Find out our Python Training in Top Cities/Countries
Python Program to Check Prime Number
A prime number is always positive and it will be checked at the beginning of the program. Here, you will divide the input number by all the numbers to see whether there are any positive divisors other than 1 and number itself. If any divisor is found then we display that the “number is not a prime number” else we display that the “number is a prime number”.
Python program:
Output: 13 is a prime number
There are different ways to optimize the prime number program in Python:
- Instead of checking till n, we can check till √n because a larger factor of n must be a multiple of smaller factor that has been already checked.
- The algorithm can be improved further by observing that all primes are of the form 6k ± 1, with the exception of 2 and 3. This is because all integers can be expressed as (6k + i) for some integer k and for i = ?1, 0, 1, 2, 3, or 4; 2 divides (6k + 0), (6k + 2), (6k + 4); and 3 divides (6k + 3). So a more efficient method is to test if n is divisible by 2 or 3, then to check through all the numbers of form 6k ± 1.
With this, we have come to the end of our article. I hope you understood how to write a prime number program in Python Programming .
To get in-depth knowledge of Python along with its various applications, you can enroll for a live Python Certification Course with 24/7 support and lifetime access.
Got a question for us? Please mention it in the comments section of this “Prime Number Program in Python” blog and we will get back to you as soon as possible or join our Master Python programming course today.
Stay ahead of the curve in technology with This Post Graduate Program in AI and Machine Learning in partnership with E&ICT Academy, National Institute of Technology, Warangal. This Artificial Intelligence Course is curated to deliver the best results.
Recommended videos for you
Application of clustering in data science using real-time examples, data science : make smarter business decisions, python programming – learn python programming from scratch, business analytics decision tree in r, diversity of python programming, 3 scenarios where predictive analytics is a must, introduction to business analytics with r, web scraping and analytics with python, android development : using android 5.0 lollipop, python loops – while, for and nested loops in python programming, python list, tuple, string, set and dictonary – python sequences, the whys and hows of predictive modeling-ii, mastering python : an excellent tool for web scraping and data analysis, know the science behind product recommendation with r programming, python classes – python programming tutorial, the whys and hows of predictive modelling-i, python tutorial – all you need to know in python programming, linear regression with r, machine learning with python, sentiment analysis in retail domain, recommended blogs for you, everything you need to know about python environment, 10 skills to master for becoming a data scientist, everything you need to know about substring in python, collections in python : everything you need to know about python collections, latest machine learning projects to try in 2019, machine learning engineer vs data scientist : career comparision, why python programming language is a must have skill, if else in python with examples : everything you need to know, world cup 2018: 5 game changing technologies in football, all you need to know about eval in python, machine learning algorithms, what do you know about business analytics with r, what is numpy in python – introduction to numpy – numpy tutorial, join the discussion cancel reply, trending courses in data science, data science and machine learning internship ....
- 1k Enrolled Learners
- Weekend/Weekday
Python Certification Training Course
- 43k Enrolled Learners
Data Science with Python Certification Course
- 113k Enrolled Learners
Python Machine Learning Certification Trainin ...
- 14k Enrolled Learners
Data Analytics with R Programming Certificati ...
- 27k Enrolled Learners
Data Science with R Programming Certification ...
- 40k Enrolled Learners
SAS Training and Certification
- 6k Enrolled Learners
Statistics Essentials for Analytics
- 7k Enrolled Learners
Analytics for Retail Banks
- 2k Enrolled Learners
Decision Tree Modeling Using R Certification ...
Browse categories, subscribe to our newsletter, and get personalized recommendations..
Already have an account? Sign in .
20,00,000 learners love us! Get personalised resources in your inbox.
At least 1 upper-case and 1 lower-case letter
Minimum 8 characters and Maximum 50 characters
We have recieved your contact details.
You will recieve an email from us shortly.

Python Program for Prime Number
What is prime number.
A positive natural number greater than 1, which only divisible by itself and 1 is known as a prime number.
For example, 23 is a prime number because it is only divisible by 1 and itself whereas 24 is not a prime number because it is divisible by 1,2,3,4,6,8,12 and itself.
In this tutorial, you will learn how to write a python program to check whether a number is a prime number or not.
Python Program to Check Prime Number
Approach of program.
- The first thing you need to check in the program is that the input variable must be greater than 1 as mentioned above prime number is greater than 1.
- The second thing you need to check is if the input num is exactly divisible by any number from 2 to num - 1. If in case you find a factor in that range, then the number is not prime or else the number is prime.
1) Check Prime Number Using For Loop
Explanation
In the above code, the input() method is used for obtaining ‘num’ value from the user. We know number less than or equal to 1 are not prime numbers thus we only perform an operation on the value if ‘num’ greater than 1.

If ‘num’ is greater than 1 is true the for loop is executed. This loop checks the numbers between 2 and the number entered by the user. For every number within this range, another if statement is executed with the code if (number % i) == 0 . If this condition is True, a string is printed using the statement print(num, is not a prime number) . Otherwise, a print statement print(num, is a prime number) is printed. The last else statement is executed when the number entered is less than or equal to 1.
According to the output, the user has entered 9 as the number. As it is not a prime number, the string " 9 is not a prime number " is printed to the screen. But when 23 is entered, the string " 23 is a prime number " is printed.
2) Check Prime Number Using While Loop
In the program, the input method is used for fetching a number from the user to evaluate if it is a prime number. After converting the value to an integer, the value is stored in the variable num . Then, a variable i is assigned a value 2. The flag variable is assigned a value 0.

In the next line, A while loop is executed that runs as long as the i variable is less than the num variable. Inside the while loop, an if statement checks the modulation value of the number divided by the i variable. If the modulation value is 0, then the flag variable is assigned the value of 1. Then a break statement moves the control out of the loop.
Outside the loop, the i variable is incremented by 1. The last part of the code checks the flag value. If the value of the flag variable is equal to 0, a print statement displays "is a prime number" along with the number.
If the flag value is 1, the string "9 is not a prime number" is displayed.
So, when the user enters 9, the string is not prime a prime number” is printed. But, when the number 23 is entered, the string "23 is a prime number” is printed.
As a prime number is supposed to be a positive integer, the program checks the condition at the beginning. So, it is best to enter a positive value for checking whether it is prime or not.
- Python Training Tutorials for Beginners
- Square Root in Python
- Python vs PHP
- Python lowercase
- Python String Replace
- Python String find
- Polymorphism in Python
- Inheritance in Python
- Python : end parameter in print()
- Python String Concatenation
- Python input()
- Python String Contains
- Python eval
- Python Reverse String
- Bubble Sort in Python
- Convert List to String Python
- Python list append and extend
- indentationerror: unindent does not match any outer indentation level in Python
- Python Return Outside Function
- Pangram Program in Python
- Learn Python Programming
- Python Online Compiler
- Addition of two numbers in Python
- Null Object in Python
- TypeError: 'int' object is not subscriptable
- pip is not recognized
- Python Comment
- Python Min()
- Python Factorial
- Python Continue Statement
- Armstrong Number in Python
- Python Uppercase
- Python map()
- Python Max() Function
- Invalid literal for int() with base 10 in Python
- Top Online Python Compiler
- Python Pass Statement
- Python Enumerate
- Python New 3.6 Features
- Python zip()
- Python Range
- Install Opencv Python PIP Windows
- Python String Title() Method
- String Index Out of Range Python
- Python Print Without Newline
- Id() function in Python
- Python Split()
- Reverse Words in a String Python
- Ord Function in Python
- Only Size-1 Arrays Can be Converted to Python Scalars
- Area of Circle in Python
- Attribute Error Python
- Python Combine Lists
- Python slice() function
- Python Sort Dictionary by Key or Value
- Remove Punctuation Python
- Compare Two Lists in Python
- Python Infinity
- Python KeyError

IMAGES
VIDEO
COMMENTS
Program to Check Prime Number ... Enter a positive integer: 29 29 is a prime number. In the program, a for loop is iterated from i = 2 to i < n/2 . ... If n is
We could have used the range, range(2,num//2) or range(2,math.floor(math.sqrt(num)+1)) . The latter range is based on the fact that a composite number must have
Prime Numbers ; C++. // C++ program to check whether a number. // is prime or not using recursion. #include <iostream>. using namespace std; ; Java. // Java
#include<stdio.h> · int main(){ · int n,i,m=0,flag=0; · printf("Enter the number to check prime:"); · scanf("%d",&n); · m=n/2; · for(i=2;i<=m;i++) · {
Prime Number Check Program in C · 1st iteration: i = 1; i <= 5; i++ here i is incremented i.e. i value for next iteration is 2 · 2nd iteration: i = 2; i <= 5; i++
Algorithm to Find Prime Number. STEP 1: Take num as input. STEP 2: Initialize a variable temp to 0. STEP 3: Iterate a “for”
Example C program for prime number: · main() · int i, num, p = 0; · printf("Please enter a number: \n"); · scanf("%d", &num); · for(i=1; i<=num; i++) · { · if(num%i==0).
Few prime number are − 1, 2, 3, 5 , 7, 11 etc. Algorithm. Algorithm of this program is very easy − START Step 1 → Take integer variable A Step 2 → Divide
The numbers 2, 3, 5, 7, etc. are prime numbers as they do not have any other factors. To find a prime number in Python, you have to iterate the value from start
2) Check Prime Number Using While Loop ... In the program, the input method is used for fetching a number from the user to evaluate if it is a prime number. After