C++ Program to Check Whether a Number Can be Express as Sum of Two Prime Numbers

13/05/2024 0 By indiafreenotes

To determine whether a given number can be expressed as the sum of two prime numbers, you can create a C++ program that incorporates a function to check if a number is prime and then verifies every possible pair of prime numbers to see if their sum equals the target number.

C++ Code:

#include <iostream>

using namespace std;

// Function to check if a number is prime

bool isPrime(int num) {

    if (num <= 1) return false;

    for (int i = 2; i * i <= num; i++) {

        if (num % i == 0) {

            return false;

        }

    }

    return true;

}

// Function to check if a number can be expressed as the sum of two prime numbers

void checkPrimeSum(int number) {

    bool canBeExpressed = false;

    for (int i = 2; i <= number / 2; i++) {

        if (isPrime(i) && isPrime(number – i)) {

            cout << number << ” can be expressed as the sum of ” << i << ” and ” << number – i << “.” << endl;

            canBeExpressed = true;

        }

    }

    if (!canBeExpressed) {

        cout << number << ” cannot be expressed as the sum of two prime numbers.” << endl;

    }

}

int main() {

    int number;

    // Prompt user to enter a number

    cout << “Enter a number: “;

    cin >> number;

    // Function call to check for expression as sum of two primes

    checkPrimeSum(number);

    return 0;

}

Explanation:

  1. Prime Checking Function (isPrime):

This function verifies if a given number is prime by checking divisibility from 2 up to the square root of the number. It returns true for prime numbers and false for non-prime numbers.

  1. Function to Check Prime Sum (checkPrimeSum):

The function iterates through all numbers from 2 to number/2 (optimization to avoid redundant checks). For each number i, it checks if both i and number – i are prime. If so, it prints that the input number can be expressed as a sum of these two primes. If no such pair is found after checking all possibilities, it prints that the number cannot be expressed as the sum of two prime numbers.

  1. Main Function:

The main function prompts the user for a number, then calls checkPrimeSum to determine if it can be expressed as the sum of two prime numbers.

Sample Output:

If the user inputs 34, the output would be:

Enter a number: 34

34 can be expressed as the sum of 3 and 31.

34 can be expressed as the sum of 5 and 29.

34 can be expressed as the sum of 11 and 23.

34 can be expressed as the sum of 17 and 17.

This program demonstrates how to use basic functions in C++ to solve problems involving prime numbers and combinations. It’s an efficient way to utilize the computation of prime numbers in different contexts.