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

Print all Prime Numbers in an Interval

Find the Factorial of a Number

Related Topics

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 .

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

GATE CS & IT 2024

Mastering Data Analytics

Related Articles

Prime Numbers

What are prime numbers?

Prime numbers

DSA Self Paced Course

Some interesting facts about Prime numbers:

Properties of prime numbers:

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.

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

Algorithms to find all prime numbers smaller than the N. 

More problems related to Prime number 

Solve DSA problems on GfG Practice.

Please Login to comment...

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.

Javatpoint Logo

C Interview

JavaTpoint

Help Others, Please Share

facebook

Learn Latest Tutorials

Splunk tutorial

Transact-SQL

Tumblr tutorial

Reinforcement Learning

R Programming tutorial

R Programming

RxJS tutorial

React Native

Python Design Patterns

Python Design Patterns

Python Pillow tutorial

Python Pillow

Python Turtle tutorial

Python Turtle

Keras tutorial

Preparation

Aptitude

Verbal Ability

Interview Questions

Interview Questions

Company Interview Questions

Company Questions

Trending Technologies

Artificial Intelligence

Artificial Intelligence

AWS Tutorial

Cloud Computing

Hadoop tutorial

Data Science

Angular 7 Tutorial

Machine Learning

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures

DAA tutorial

Operating System

Computer Network tutorial

Computer Network

Compiler Design tutorial

Compiler Design

Computer Organization and Architecture

Computer Organization

Discrete Mathematics Tutorial

Discrete Mathematics

Ethical Hacking

Ethical Hacking

Computer Graphics Tutorial

Computer Graphics

Software Engineering

Software Engineering

html tutorial

Web Technology

Cyber Security tutorial

Cyber Security

Automata Tutorial

C Programming

C++ tutorial

Control System

Data Mining Tutorial

Data Mining

Data Warehouse Tutorial

Data Warehouse

Javatpoint Services

JavaTpoint offers too many high quality services. Mail us on [email protected] , to get more information about given services.

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

RSS Feed

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 example for prime number:

What is prime number?

A number is considered as prime number when it satisfies the below conditions.

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:.

Learn C By Examples Tutorial

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 −

FlowDiagram Even Odd

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

What is Python language? Is it easy to learn?

Top 10 Reasons Why You Should Learn Python

Python Installation

Python Fundamentals

Init In Python: Everything You Need To Know

Learn How To Make Python Pattern Programs With Examples

Python For Loop Tutorial With Examples To Practice

Python OOPs

Python Libraries

Web Scraping

Python Programs

How to Find Prime Numbers in Python

Career Oppurtunities

Python career opportunities: your career guide to python programming.

Interview Questions

Top 100+ python interview questions you must prepare in 2023.

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:

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:

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 ....

Python Certification Training Course

Data Science with Python Certification Course

Python Machine Learning Certification Trainin ...

Data Analytics with R Programming Certificati ...

Data Science with R Programming Certification ...

SAS Training and Certification

Statistics Essentials for Analytics

Analytics for Retail Banks

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.

Online Tutorials & Training Materials | STechies.com

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.

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.

Python Prime Number Using For Loop

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.

Python Prime Number Using While Loop

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.

IMAGES

  1. C Program to Find Sum of All Prime Numbers Between 1 to N

    write program to check prime number

  2. Prime Numbers with Loops in C. This is a common assignment, test and…

    write program to check prime number

  3. Prime Number Logic In Java

    write program to check prime number

  4. Python Program to Check If a number is Prime or not

    write program to check prime number

  5. Prime number program in c

    write program to check prime number

  6. write a program to check whether a number is prime or not

    write program to check prime number

VIDEO

  1. Prime Number Program in C, C++ and Java

  2. C Program to Check Prime Number #shorts #youtubeshorts #cprogramming #viral

  3. write a program to check whether a numbers is prime or not in C Language ||#shorts #short

  4. Python program to calculate the length of a string

  5. python program to check prime number

  6. CAN YOU CREATE? Prime number checker with Python #python #youtube #youtubeshorts #youtuber #coding

COMMENTS

  1. C Program to Check Whether a Number is Prime or Not

    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

  2. Python Program to Check Prime Number

    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

  3. Prime Numbers

    Prime Numbers ; C++. // C++ program to check whether a number. // is prime or not using recursion. #include <iostream>. using namespace std; ; Java. // Java

  4. Prime Number program in C

    #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++) · {

  5. C Program to Check whether the Given Number is a Prime

    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++

  6. C Program For Prime Numbers: True or False

    Algorithm to Find Prime Number. STEP 1: Take num as input. STEP 2: Initialize a variable temp to 0. STEP 3: Iterate a “for”

  7. C Program for Prime number

    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).

  8. Prime Number Program In C

    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

  9. How to Write a Prime Number Program in Python

    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

  10. Python Program for Prime Number

    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