Problem
Find out if a given number can be expressed as sum of two prime numbers or not.
Given a positive integer N, we need to check if the number N can be represented as a sum of two prime numbers.
Solution
Consider an example given below −
20 can be expressed as sum of two prime numbers 3 and 17, 13 and 7.
20= 3+7
20= 13+7
Algorithm
Refer an algorithm given below for expressing a given number as a sum of two prime numbers.
Step 1 − Input the number to be checked at run time.
Step 2 − Repeat from i = 2 to (num/2).
Step 3 − Check i is a prime number.
Step 4 − If i is prime, check if (n - i) is a prime number.
Step 5 − If both (i)and (n - i) are primes, then, the given number can be represented as the sum of primes i and (n - i).
Example
Following is the C program for expressing a given number as a sum of two prime numbers −
#include <stdio.h> int Sum(int n); int main(){ int num, i; printf("Enter number: "); scanf("%d", &num); int flag = 0; for(i = 2; i <= num/2; ++i){ if (sum(i) == 1){ if (sum(num-i) == 1){ printf("\nThe given %d can be expressed as the sum of %d and %d\n\n", num, i, num - i); flag = 1; } } } if (flag == 0) printf("The given %d cannot be expressed as the sum of two prime numbers\n", num); return 0; } //check if a number is prime or not int sum(int n){ int i, isPrime = 1; for(i = 2; i <= n/2; ++i){ if(n % i == 0){ isPrime = 0; break; } } return isPrime; }
Output
When the above program is executed, it produces the following output −
Run 1: Enter number: 34 The given 34 can be expressed as the sum of 3 and 31 The given 34 can be expressed as the sum of 5 and 29 The given 34 can be expressed as the sum of 11 and 23 The given 34 can be expressed as the sum of 17 and 17 Run 2: Enter number: 11 The given 11 cannot be expressed as the sum of two prime numbers