fastread homefastrread library fastread menu

C : Check Whether a Number can be Express as Sum of Two Prime Numbers

Tutorial by:Manisha Dubey      Date: 2016-06-17 03:49:59

❰ Previous Next ❱

Example to check if an integer (entered by the user) can be expressed as the sum of two prime numbers of all possible combinations by making a function.

To accomplish this task, checkPrime() function is created.

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

Example: Integer as a Sum of Two Prime Numbers

#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 can't be expressed as the sum of two prime numbers.", n);
    return 0;
}

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

    for(i=2; i<=n/2; ++i)
    {
        if(n%i==0)
            flag=0;
    }

    return flag;
}

 

 
 

Output

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

❰ Previous Next ❱


C

Submit Your Thought, Tutorial, Articls etc.

Submit Your Information India's Number one online promotion website