C++ Online Compiler
Example: Check if a Number is Sum of Two Primes in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Check if a Number is Sum of Two Primes #include <iostream> // For input/output operations #include <cmath> // For sqrt function // Function to check if a number is prime bool isPrime(int num) { // Step 1: Handle edge cases for primality if (num <= 1) { return false; // Numbers less than or equal to 1 are not prime } // Step 2: Check divisibility from 2 up to the square root of num // We only need to check up to sqrt(num) because if num has a divisor // greater than sqrt(num), it must also have one smaller than sqrt(num). for (int i = 2; i <= sqrt(num); ++i) { if (num % i == 0) { return false; // If divisible, it's not prime } } // Step 3: If no divisors found, it's prime return true; } int main() { int n; // Step 1: Prompt user for input std::cout << "Enter a positive integer: "; std::cin >> n; // Step 2: Check if the number can be expressed as sum of two primes bool found = false; // Flag to track if a pair is found for (int i = 2; i <= n / 2; ++i) { // Step 3: Check if 'i' is prime if (isPrime(i)) { // Step 4: Check if 'n - i' is prime if (isPrime(n - i)) { // Step 5: If both are prime, print the result and set flag std::cout << n << " can be expressed as sum of two prime numbers: " << i << " + " << (n - i) << std::endl; found = true; break; // Found a pair, no need to check further } } } // Step 6: If no pair was found after checking all possibilities if (!found) { std::cout << n << " cannot be expressed as sum of two prime numbers." << std::endl; } return 0; // Indicate successful execution }
Output
Clear
ADVERTISEMENTS