Home / Programs / C Program - Integer as a Sum of Two Prime Numbers
Programming Example

C Program - Integer as a Sum of Two Prime Numbers

👁 1,189 Views
💻 Practical Program
📘 Step by Step Learning

Integer as a Sum of Two Prime Numbers.

Information & Algorithm

If you don't know what is prime number please read form this tutorial. Prime Number & Prime Factors

Program Code

#include <stdio.h>
int checkPrime(int n);
int main()
{
    int n, i, flag = 0;

    printf("Enter a positive integer: ");
    scanf("%d", &n);

    for(i = 2; i <= n/2; ++i)
    {
        // condition for i to be a prime number
        if (checkPrime(i) == 1)
        {
            // condition for n-i to be a prime number
            if (checkPrime(n-i) == 1)
            {
                // n = primeNumber1 + primeNumber2
                printf("%d = %d + %d\n", n, i, n - i);
                flag = 1;
            }

        }
    }

    if (flag == 0)
        printf("%d cannot be expressed as the sum of two prime numbers.", n);

    return 0;
}

// Function to check prime number
int checkPrime(int n)
{
    int i, isPrime = 1;

    for(i = 2; i &lt;= n/2; ++i)
    {
        if(n % i == 0)
        {
            isPrime = 0;
            break;
        }  
    }

    return isPrime;
}

Output

Enter a positive integer: 34
34 = 3 + 31
34 = 5 + 29
34 = 11 + 23
34 = 17 + 17

Explanation

To understand this example, you should have the knowledge of following C programming topics:

C if, if...else and Nested if...else Statement
C Programming for Loop
C Programming Functions
C Programming User-defined functions
To accomplish this task, checkPrime() function is created.

The checkPrime() returns 1 if the number passed to the function is a prime number.

How to learn from this program

First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.