Skip to main content

Check if a Number is Prime with Simple C++ Code

Determining whether a number is prime is a common task in programming and mathematics. A prime number is defined as a natural number greater than 1 that cannot be formed by multiplying two smaller natural numbers. In this blog post, we’ll explore a straightforward C++ code snippet that checks if a given number is prime or not.

#include<iostream>
using namespace std;

main()
{
    int n, num = 2, flag = 0;
    cin >> n; // Read an integer from user input

    // Check for primality
    while (num < n)
    {
        if (n % num == 0)
        {
            cout << "Not Prime" << endl; // Print "Not Prime" if 'n' is divisible by 'num'
            flag = 1; // Set flag to 1 indicating that 'n' is not prime
            break; // Exit the loop as we have found a divisor
        }
        num++; // Increment 'num' to check the next divisor
    }
   
    if (flag == 0)
        cout << "Prime" << endl; // Print "Prime" if no divisors were found
}

How the Code Works

1. Input Reading

The code begins by reading an integer input from the user, which is stored in the variable n.

2. Initial Setup

  • num: This variable starts at 2 and will be used to check possible divisors of n.
  • flag: A flag is set to 0 initially. It will be used to indicate whether a divisor has been found.

3. Checking for Divisors

The code enters a while loop that runs as long as num is less than n. Inside the loop:

  • Divisibility Check: The condition if (n % num == 0) checks if n is divisible by num without leaving a remainder.
    • If True: This means n is not a prime number (as it has a divisor other than 1 and itself). The code prints "Not Prime", sets flag to 1, and breaks out of the loop.
    • If False: The loop continues with num incremented by 1 to check the next possible divisor.

4. Final Check

After the loop, if flag is still 0, it means no divisors were found other than 1 and n itself. Therefore, n is a prime number, and the code prints "Prime".

Why This Code Works

  • Efficiency: The loop runs only until num is less than n. For each iteration, it checks if n is divisible by the current num.
  • Correctness: If n is divisible by any number other than 1 and itself, it is correctly identified as "Not Prime". If no such divisors are found, n is correctly identified as "Prime".

Potential Improvements

  • Optimize Divisor Check: Instead of checking up to n, you could check up to the square root of n. This would make the code more efficient for larger numbers.
  • Edge Cases: The code does not handle numbers less than 2. It would be beneficial to include checks for such cases and handle them appropriately.

SEO Keywords: C++ prime number check, is number prime C++, prime number C++ code, check for primality in C++, C++ programming tutorial, determine prime number C++

Popular posts from this blog

BCA 5th and 6th Semester Project | BCSP-064 | Synopsys and Project | Both | IGNOU BCA | 100% Accepted | July 2023 and Jan 2024

 Synopsys and Project | Both | July 2023 and Jan 2024 Title of the Project : - PRODUCT HUB Buy it from here (Synopsis + Project) : Synopsis Content :- Synopsis : An overview of the entire project, summarizing its main objectives, scope, and outcomes. Introduction : Introduce the project and provide context for the reader by explaining the problem or need that the project aims to address. Aim and Objective : Clearly state the goals and objectives of the project, outlining what you intend to achieve through its completion. Project Category : Define the domain or category to which the project belongs, helping readers understand the context and purpose of the project. Tools and Platform : List the software tools, programming languages, and platforms you'll be using to develop and implement the project. System Analysis : Discuss the preliminary analysis phase of the project, where you identify requirements,

Flowchart and Pseudocode to Find the Area of a Square

  Write a flowchart and pseudocode to find the area of a square. Pseudocode :-  1. Start 2. Input length of the square 3. Calculate area of square as length * length 4. Print area 5. End #C++Programming Language #codeDelhi

MCS-021 | Data and File Structures | IGNOU BCA Solved Assignment | July 2021 & January 2022

  Course Code :- MCS-021 Course Title :- Data and File Structures Assignment Number :- BCA(3)/021/Assignment/2021-22 Maximum Marks :-  100 Weightage :-   25% Last Dates for Submission :- 31st October, 2021 (For July Session) &  15th April, 2022 (For January Session)  This assignment has four questions which carry 80 marks. Answer all the questions. Each question carries 20 marks. You may use illustrations and diagrams to enhance the explanations. Please go through the guidelines regarding assignments given in the Programme Guide. All the implementations should be in C programming language. Question 1: Write an algorithm that accepts a Binary Tree as inputs and outputs the traversals of Inorder , Postorder and Preorder of it. Question 2: Is it possible to implement multiple queues in a Stack. Justify your answer.  Question 3: List the names of all Sorting Algorithms along with their Complexities (Best case, Average case and Worst case). List as many names as possible along