Advertisement

C++ Program to check the square root of a number is prime or not


In this program, You will learn how to check the square root of a number is prime or not in C++.


64 => 4 : not prime

49 => 7 : number is Prime

Example: How to check the square root of a number is prime or not in C++

#include<iostream>
#include<math.h>
using namespace std;

int main() {
    int x, y = 1, z, i;
    float root;

    cout << "Enter a number:";
    cin>>x;

    z = root = sqrt(x);
    cout << "Number square root is:" << root;

    if (z == 1) {
        cout << "\nNumber is not prime";
    } else {
        for (i = 2; i < z; i++) {
            if (z % i == 0) {
                y = 0;
                break;
            }
        }
        if (y == 1) {
            cout << "\nNumber is prime:" << z;
        } else {
            cout << "\nNumber is not prime:" << z;
        }
    }

    return 0;
}

Output:

Enter a number:49
Number square root is:7
Number is prime:7