Prime Number in C++


Q. Write a C++ program to check Prime Number or Not.

#include <iostream>      
using namespace std;
  
int main()
{  
    int n, i, flag = 0;
    cout << "Enter the number: ";
    cin >> n;
    for(i = 2; i <= n/2; i++)
    {
        if(n%i == 0)
        {
            flag = 1;
            break;
        }
    }
    if ( n<=1) 
    {
      cout << "Prime number is greater than 1.";
    }
    else 
    {
        if (flag == 0)
          cout << n << " is a prime number." ;
        else
          cout << n << " is not a prime number." ;
    }
}

Write an algorithm to check Prime Number or Not.

1. Start
2. Input the integer number `n`.
3. If `n` is less than or equal to 1
- Print `"Prime number is greater than 1."`
- End
4. Initialize a variable `flag` to 0 (this will indicate whether `n` has a divisor other than 1 and itself)
5. For `i` from 2 to `n/2` do:
- If `n` modulo `i` equals 0 (i.e., `n % i == 0`) then:
- Set `flag` to 1 (indicating `n` is divisible by `i`)
- Break out of the loop
6. After the loop, check the value of `flag`:
- If `flag` is 0, print `n` is a prime number
- Otherwise, print `n` is not a prime number
7. End



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.