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) {
        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: 34
34 = 3 + 31
34 = 5 + 29
34 = 11 + 23
34 = 17 + 17

In this program, we use the checkPrime() function to check whether a number is prime or not.

In main(), we take a number from the user and store it in the variable n.

We also initialize the int variable flag to 0. We use this variable to determine whether the input number can be expressed as the sum of two prime numbers.

 

We then iterate a loop from i = 2 to i = n/2. In each iteration, we check whether i is a prime number or not.

If i is a prime, we check whether n – i is prime or not.

If n – i is also a prime, then we know that n can be expressed as the sum of two prime numbers i and n – i.

So, we print the result on the screen and change the value of flag to 1. Otherwise, flag remains 0.

This process continues until the loop ends.

If flag is still 0, then we know that n can’t be expressed as the sum of two primes, and we print that message on the screen.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *