C++ Online Compiler
Example: Check Prime Number by User-defined Function in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Check Prime Number by User-defined Function #include <iostream> #include <cmath> // Required for sqrt() function // Function to check if a number is prime bool isPrime(int num) { // Step 1: Handle edge cases if (num <= 1) { return false; // Numbers less than or equal to 1 are not prime } if (num == 2) { return true; // 2 is the only even prime number } if (num % 2 == 0) { return false; // All other even numbers are not prime } // Step 2: Check for divisibility from 3 up to sqrt(num) // We only need to check odd divisors for (int i = 3; i <= sqrt(num); i += 2) { if (num % i == 0) { return false; // Found a divisor, so it's not prime } } // Step 3: If no divisors were found, the number is prime return true; } int main() { // Step 1: Declare a variable to store user input int number; // Step 2: Prompt the user to enter a number std::cout << "Enter a positive integer: "; std::cin >> number; // Step 3: Call the isPrime function and display the result if (isPrime(number)) { std::cout << number << " is a prime number." << std::endl; } else { std::cout << number << " is not a prime number." << std::endl; } return 0; }
Output
Clear
ADVERTISEMENTS