top of page

Write a Program in C++ to check whether the given Number is Prime or Composite Number.

Prime Number

A prime number is a number that can only be divided by itself and 1 without remainders. A prime number cannot be divided by any other numbers without leaving a remainder. An example of a prime number is 13. It can only be divided by 1 and 13. Dividing a prime number by another number results in numbers left over e.g. 13 ÷ 6 = 2 remainder 1.

Composite Number

Composite numbers can be defined as natural numbers that have more than two factors. In other words, a number that is divisible by a number other than 1 and the number itself, is called a composite number. 4, 6, 8, 9, and 10 are the first few composite numbers. Let's take 4 and 6. In the above example, 4 and 6 are called composite numbers because they are made by combining other numbers.


#include <iostream>
#include <math.h>

using namespace std;

//Returns true if the given number is a Prime number
bool isPrime(int n)
    if (n == 1)
        return false; // as 1 is not a prime number

    for (int i = 2; i <= sqrt(n); i++) // Complexity O(SquareRoot(n))
        if (n % i == 0)
            return false;

    return true;

int main()
    //variable declaration
    int n;
    bool prime = false;

    //taking input from the command line (user)
    cout << " Enter a positive integer other than 1 :  ";
    cin >> n;

    //Calling a method that returns true if the number is Prime
    prime = isPrime(n);

    if (prime)
        cout << "\n\nThe entered number " << n << " is a Prime number.";
        cout << "\n\nThe entered number " << n << " is Composite number.";

    cout << "\n\n\n";

    return 0;


The Tech Platform

bottom of page