Check Whether a Number can be Expressed as Sum of Two Prime Numbers in C

Exercise:

Write a C Program to check whether a number can be expressed as sum of two prime numbers.

Click Here to View the Solution!
#include <stdio.h>
int checkIntPrime(int num);

int main() {
    int num, i; 
    int flag = 0;
    printf("Enter a positive integer: ");
    scanf("%d", &num);

    for (i = 2; i <= num / 2; ++i) {
        if (checkIntPrime(i) == 1) {
            if (checkIntPrime(num - i) == 1) {
                printf("%d = %d + %d\n", num, i, num - i);
                flag = 1;
            }
        }
    }
    if (flag == 0)
        printf("%d cannot be expressed as the sum of two prime numbers.", num);
    return 0;
}

int checkIntPrime(int num) {
    int i, isIntPrime = 1;
    for (i = 2; i <= num / 2; ++i) {
        if (num % i == 0) {
            isIntPrime = 0;
            break;
        }
    }
    return isIntPrime;
}
Click Here to View the Output!
Enter a positive integer: 4 
4 = 2 + 2  
Click Here to View the Explanation!
  • This program is used to check whether a number can expressed as a sum of two prime numbers.
  • A function checkIntPrime is initialized.
  • In main(), the program requests the use to enter a positive integer and stores it in the variable num using the scanf() function.
  • A for loop is initialized with a condition that will iterate between i = 2 and i <= num/2 and each time i will be incremented.
  • A condition in the if statement will be set which will check whether i is a prime number. And another if statement to check whether num-i is a prime number.
  • If both if statements will be true, i and num-i will be added to check if their sum is equal to num and the flag will be set to 1.
  • If the flag will be 0, a message will be printed that the number cannot be expressed as a sum of two prime numbers.
  • The function checkIntPrime is created at the end which will check whether num is exactly divisible by i, if true, the variable isPrime will be set to 0 else will remain 1 and will be returned.

%d bloggers like this: