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

C++ Program to Check Prime Number

Last Updated : 05 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

A Prime Number is a natural number greater than 1 that has no positive divisors other than 1 and itself.

Examples:

Input: n = 29
Output: 29 is prime
Explanation: 29 has no divisors other than 1 and 29 itself. Hence, it is a prime number.

Input: n = 15
Output: 15 is NOT prime
Explanation: 15 has divisors other than 1 and 15 (i.e., 3 and 5). Hence, it is not a prime number.

There are many approaches for checking whether the given number is a prime number:

Table of Content

  • Brute Force Method – O(n) Time
  • Optimized Method – O(√n) Time

Brute Force Method – O(n) Time

In this approach, we can check whether the number is prime or not by iterating in the range from 1 to n. If there are more than 2 divisor (including 1 and n) then the given number n is not prime, else n is prime. This method is known as trial division method.

C++
//Driver Code Starts{ #include <bits/stdc++.h> using namespace std;  int main() { //Driver Code Ends }      int n = 29;     int cnt = 0;          // If number is less than/equal to 1,     // it is not prime     if (n <= 1)         cout << n << " is NOT prime";     else {          // Count the divisors of n         for (int i = 1; i <= n; i++) {             if (n % i == 0)                 cnt++;         }          // If n is divisible by more than 2          // numbers then it is not prime         if (cnt > 2)             cout << n << " is NOT prime";          // else it is prime         else             cout << n << " is prime";     }  //Driver Code Starts{     return 0; } //Driver Code Ends } 

Output
29 is prime

The time complexity of the above program is O(n) because we iterate from 1 to n.

Optimized Method – O(√n) Time

In this approach, we don’t check all divisors of the given number, we only check divisors up to the square root of the number because, “The smallest factor of a number greater than one cannot be greater than the square root of that number.”

C++
//Driver Code Starts{ #include <bits/stdc++.h> using namespace std;  int main() { //Driver Code Ends }      int n = 29;     int cnt = 0;          // If number is less than/equal to 1,     // it is not prime     if (n <= 1)         cout << n << " is NOT prime";     else {          // Count the divisors of n         for (int i = 2; i * i <= n; i++) {             if (n % i == 0)                 cnt++;         }          // If n is divisible by more than 2          // numbers then it is not prime         if (cnt > 0)             cout << n << " is NOT prime";          // else it is prime         else             cout << n << " is prime";     }  //Driver Code Starts{     return 0; } //Driver Code Ends } 

Output
29 is prime

The time complexity of the above program is O(√n) because we iterate only √n times.

We can further optimize the above approach by skipping all even numbers greater than 2. Since the only even prime number is 2, we can skip all even numbers between 3 and √n.

C++
//Driver Code Starts{ #include <bits/stdc++.h> using namespace std;  int main() { //Driver Code Ends }      int n = 29;     int cnt = 0;      // If number is less than/equal      // to 1 and number is even accept 2     // then it is not prime     if (n <= 1 || ((n > 2) && (n%2 == 0)))         cout << n << " is NOT prime";     else {         if (n == 2) {             cout << n << " is prime";             return 0;         } else {              // Check how many numbers divide              // n in the range 2 to sqrt(n)             for (int i = 3; i * i <= n; i += 2) {                 if (n % i == 0)                     cnt++;             }              // if cnt is greater than 0,              // then n is not prime             if (cnt > 0)                 cout << n << " is NOT prime";              // else n is prime             else                 cout << n << " is prime";         }     }  //Driver Code Starts{     return 0; } //Driver Code Ends } 

Output
29 is prime


Next Article
C++ Program To Find Prime Numbers Between Given Interval
author
kartik
Improve
Article Tags :
  • C++
  • C++ Programs
  • C++ Basic Programs
Practice Tags :
  • CPP

Similar Reads

  • C++ Program To Check Whether a Number is Prime or not
    Given a positive integer N. The task is to write a C++ program to check if the number is prime or not.  Definition:  A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. The first few prime numbers are {2, 3, 5, 7, 11, ....} The idea to solve this
    3 min read
  • C++ Program to Print Prime Numbers from 1 to n
    A prime number is a natural number that has only two divisors, which are 1 and itself. In this article, we will learn how to print all the prime numbers from 1 to n in C++. Examples Input: n = 10Output: 2, 3, 5, 7Explanation: As 2, 3, 5, 7 are the only prime numbers between 1 to 10. Input: n = 5Outp
    5 min read
  • C++ Program to Check Whether Number is Even or Odd
    A number is even if it is completely divisible by 2 and it is odd if it is not completely divisible by 2. In this article, we will learn how to check whether a number is even or odd in C++. Examples Input: n = 11Output: OddExplanation: Since 11 is not completely divisible by 2, it is an odd number.
    4 min read
  • C Program To Find Prime Numbers Between Given Range
    A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. For example, 2, 3, 5, 7, and 11 are prime numbers. In this article, we will learn how to find all the prime numbers between the given range. Example Input: l = 10, r = 30Output: 11 13 17 19Explan
    6 min read
  • C++ Program To Find Prime Numbers Between Given Interval
    A prime number is defined as a natural number greater than 1 and is divisible by only 1 and itself. In other words, the prime number is a positive integer greater than 1 that has exactly two factors, 1 and the number itself. The first few prime numbers are 2, 3, 5, 7, 11, 13, 17, 19, 23 . . . Note:
    7 min read
  • TCS Coding Practice Question | Checking Prime Number
    Given a number N, the task is to check if N is a Prime Number or not using Command Line Arguments.Examples: Input: N = 7Output: YesInput: N = 15Output: NoApproach: Since the number is entered as Command line Argument, there is no need for a dedicated input lineExtract the input number from the comma
    4 min read
  • C++ Program for How to check if a given number is Fibonacci number?
    Given a number 'n', how to check if n is a Fibonacci number. First few Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 141, .. Examples : Input : 8 Output : Yes Input : 34 Output : Yes Input : 41 Output : No Following is an interesting property about Fibonacci numbers that can also be
    2 min read
  • C++ Program to find sum of even factors of a number
    Given a number n, the task is to find the even factor sum of a number. Examples: Input : 30 Output : 48 Even dividers sum 2 + 6 + 10 + 30 = 48 Input : 18 Output : 26 Even dividers sum 2 + 6 + 18 = 26 Let p1, p2, … pk be prime factors of n. Let a1, a2, .. ak be highest powers of p1, p2, .. pk respect
    3 min read
  • C++ Program To Check If a Prime Number Can Be Expressed as Sum of Two Prime Numbers
    Given a prime number [Tex]N  [/Tex]. The task is to check if it is possible to express [Tex]N  [/Tex]as sum of two separate prime numbers.Note: The range of N is less than 108. Examples:  Input: N = 13 Output: Yes Explanation: The number 13 can be written as 11 + 2, here 11 and 2 are both prime. Inp
    2 min read
  • TCS Coding Practice Question | Prime Numbers upto N
    Given a number N, the task is to find the Prime Numbers from 1 to N using Command Line Arguments. Examples: Input: N = 7Output: 2, 3, 5, 7 Input: N = 13Output: 2, 3, 5, 7, 11, 13 Approach: Since the number is entered as Command line Argument, there is no need for a dedicated input lineExtract the in
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

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