Uncovering the Secrets of Prime Numbers

The Problem Statement

Given a positive integer, can we find two prime numbers that add up to it? This seemingly simple problem requires a deep understanding of prime numbers and their properties.

The Solution

Our program takes a positive integer as input from the user and stores it in the variable n. We also initialize a boolean variable flag to false, which will help us determine whether the input number can be expressed as the sum of two prime numbers.

The Prime Number Check

We define a user-defined function check_prime() to verify whether a number is prime or not. This function is the backbone of our program, as it enables us to identify prime numbers within a given range.

bool check_prime(int num) {
    if (num <= 1) {
        return false;
    }
    for (int i = 2; i * i <= num; i++) {
        if (num % i == 0) {
            return false;
        }
    }
    return true;
}

The Iterative Approach

In the main() function, we iterate a loop from i = 2 to i = n/2. In each iteration, we check whether i is a prime number using our check_prime() function. If i is prime, we then check whether n - i is also prime. If both conditions are true, we’ve found a combination of two prime numbers that add up to n. We print the result on the screen and set flag to true.

int main() {
    int n;
    cout << "Enter a positive integer: ";
    cin >> n;
    bool flag = false;
    for (int i = 2; i <= n / 2; i++) {
        if (check_prime(i) && check_prime(n - i)) {
            cout << "The number " << n << " can be expressed as the sum of two prime numbers: " << i << " and " << n - i << endl;
            flag = true;
            break;
        }
    }
    if (!flag) {
        cout << "No combination of two prime numbers adds up to " << n << endl;
    }
    return 0;
}

Exploring Further

This program opens doors to more exciting possibilities in number theory. You can explore similar programs, such as:

  • Displaying prime numbers between two intervals
  • Checking prime numbers using functions

The world of prime numbers is full of mysteries waiting to be uncovered!

Leave a Reply