gpt-3.5-turbo-0613· OpenAI
WildChat-4.8M (AI2)
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 Sample Run: Input Output 2 2 is a prime number 8 8 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; }Explanation:
- The function
isPrime()takes an integernas input and returns true ifnis prime and false otherwise. - The function starts by checking if
nis less than or equal to 1. If it is, then it is not a prime number and the function returns false. - Next, the function iterates from 2 to the square root of
n(i*i <= n) and checks if is divisible by any number in that range. If it is, then it is not a prime number and the function returns false.
- The function