Write a program in C++ to check whether a number is prime or not. Hint: Prime number (p)…
- User
Write a program in C++ to check whether a number is prime or not. Hint: Prime number (p) has two factors only (1, p)
Input: Integer number n.
Output: print: n is a prime number or print : n is not a prime number
- Assistant
Here is a C++ program that checks whether a number is prime or not:
#include <iostream> using namespace std; bool isPrime(int n) { if (n <= 1) { return false; } for (int i = 2; i * i <= n; i++) { if (n % i == 0) { return false; } } return true; } int main() { int n; cout << "Enter a number: "; cin >> n; if (isPrime(n)) { cout << n << " is a prime number" << endl; } else { cout << n << " is not a prime number" << endl; } return 0; }In this program, we define a function
isPrime()that takes an integernas input and checks whether it is prime or not. The function uses a loop to iterate from 2 to the square root ofnand checks ifnis divisible by any number in this range. Ifnis divisible by any number, it returnsfalse, indicating that it is not prime. If no number dividesn, it returnstrue, indicating that it is prime.In the
main()function, we prompt the user to enter a number and then call the function to check if it is prime or not. We then print the appropriate message based on the return value of the function.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.