Can A Number Be Expressed As A Sum Of Two Prime Numbers?

Write a C program is Can a number be expressed as a sum of two prime numbers?

The program in C takes a positive integer or number which is required to be inserted by the user. The program further identifies whether that digit can be expressed as the sum of two prime numbers. If the inserted number can be expressed as sum of two prime numbers then, print the integer can be expressed as sum of two prime numbers as a result.

Can a number be expressed as a sum of two prime numbers_ in C programming

Working:-

Step 1: Start

Step 2: Ask the user to insert a number as an input.

Step 3: Initiate the value of i in a loop from 2 up to half the value of the entered number.

Step 4: Check if i is a prime number.

Step 5: If i is a prime number, identify if (n – 1) is a prime number.

Step 6: If both i and (n – 1) are prime numbers, then the given number can be represented as the sum of prime numbers i and (n – 1).

Step 7: Stop

C Program:- 

// C program to check whether a number can be expressed as a sum of two prime numbers

#include<stdio.h>   
int sum_of_two_primes(int n);
int main()
{
    int n, i;

    printf(“Insert the num: “);
    scanf(“%d”, &n);
    int flag = 0;
    for(i = 2; i <= n/2; ++i)
    {
        // Condition for i to be prime
         if(sum_of_two_primes(i) == 1)
         {
             if(sum_of_two_primes(n-i) == 1)
             {
                  printf(“\n%d can be expressed as the sum of %d and %d\n\n”, n, i, n – i);
                  flag = 1;
             }

         }
     }

     if(flag == 0)
          printf(“%d cannot be expressed as the sum of two primes\n”, n)      

return
0; } int sum_of_two_primes(int n) { int i, isPrime = 1; for(i = 2; i <= n/2; ++i) { if(n % i == 0) { isPrime = 0; break; } } return isPrime; }

Output

Insert the num: 20
20 can be expressed as the sum of 3 and 17
20 can be expressed as the sum of 7 and 13

Please Login/Signup to comment