Tuesday, March 14, 2023

Write a program in C++ to check whether the given no is prime or not.

Check Whether a Number is Prime or Not - C++ Program

Write a program in C++ to check whether the given no is prime or not.

#include <iostream>
using namespace std;

bool isPrime(int num) {
    if (num <= 1) {
        return false;
    }
    for (int i = 2; i <= num / 2; i++) {
        if (num % i == 0) {
            return false;
        }
    }
    return true;
}

int main() {
    int num;
    cout << "Enter a number: ";
    cin >> num;

    if (isPrime(num)) {
        cout << num << " is a prime number." << endl;
    } else {
        cout << num << " is not a prime number." << endl;
    }
    return 0;
}

The program first asks the user to input a number, and then calls the isPrime function to check whether the number is prime or not. The isPrime function takes an integer as input and returns a boolean value true if the number is prime, and false otherwise.

The isPrime function works as follows:

  • First, it checks if the input number is less than or equal to 1. If it is, then the function returns false, because 1 and any number less than 1 are not prime.
  • Next, it checks if the input number is divisible by any number from 2 to num / 2. If it is, then the function returns false, because a prime number is only divisible by 1 and itself.
  • If the input number is not divisible by any number from 2 to num / 2, then the function returns true, because the number is prime.

In the main function, we simply call the isPrime function with the input number, and print the appropriate message depending on whether the number is prime or not.

I hope this helps! Let me know if you have any questions.

No comments:

Post a Comment

Write a c++ program to show the difference between an array and a list.

Array vs List Example Write a c++ program to show the difference between an array and a list. Arrays are useful when you know the number ...