Google News
logo
C Program to Check Whether a Number can be Expressed as Sum of Two Prime Numbers
* This program takes a positive integer from the user and checks whether that number can be expressed as the sum of two prime numbers.

* If the number can be expressed as the sum of two prime numbers, the output shows the combination of the prime numbers.

Integer as a Sum of Two Prime Numbers :

Program :
#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) {
        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;

  // 0 and 1 are not prime numbers
  if (n == 0 || n == 1) {
    isPrime = 0;
  }
  else {
    for(i = 2; i <= n/2; ++i) {
      if(n % i == 0) {
        isPrime = 0;
        break;
      }
    }
  }

  return isPrime;
}
Output :
Enter a positive integer: 72
72 = 5 + 67
72 = 11 + 61
72 = 13 + 59
72 = 19 + 53
72 = 29 + 43
72 = 31 + 41