Check whether a number can be expressed as a sum of two prime numbers or not
C program to check whether a number can be expressed as a sum of two prime numbers or not.
Prime number is a number that is greater than 1 and is divisible only by 1 or itself. In other words, prime numbers can't be divided by other numbers than itself or 1. The first few prime numbers are {2, 3, 5, 7, 11, 13, 17 ...}
In this program, we have to check whether the entered number can be represented as a sum of two prime numbers.
For example, num = 12
So, 12 can be represented as sum of two prime numbers.
Let us see another example, num = 11
So, 11 can not be represented as sum of two prime numbers.
In this program, we have to check whether the entered number can be represented as a sum of two prime numbers.
For example, num = 12
12 = 1 + 11 | 11 is a prime number but not 1 |
12 = 2 + 10 | None of the 2 and 10 is prime |
12 = 3+ 9 | Only 3 is prime not 9 |
12 = 4 + 8 | None of 4 and 8 is prime |
12 = 5 + 7 | Both 5 and 7 are prime |
12 = 6 + 6 | 6 is not prime |
Let us see another example, num = 11
11 = 1 + 10 | None of 1 and 10 is prime |
11 = 2 + 9 | 2 is prime but not 9 |
11 = 3+ 8 | Only 3 is prime not 8 |
11 = 4 + 7 | Only 7 is prime not 4 |
11 = 5 + 6 | 5 is prime but not 6 |
Program
#include<stdio.h>
#include<conio.h>
void main()
{
int num, i, flag1=1, flag2=1, flag3=0, j;
printf("Enter the number\t:");
scanf("%d",&num);
for(i=3; i<=num/2; i++)
{
//check for prime
flag1=1;
flag2=1;
for(j=2; j<i; j++)
{
if(i%j==0)
{
flag1=0;
j=i;
}
}
for(j=2; j<num-i; j++)
{
if((num-i)%j==0)
{
flag2=0;
j=num-i;
}
}
if(flag1==1 && flag2==1)
{
printf("%d = %d + %d \n",num,i,num-i);
flag3=1;
}
}
if(flag3==0)
{
printf("\n%d can not be expressed as sum of two prime numbers.",num);
}
else
{
printf("\n%d can be expressed as sum of two prime numbers.",num);
}
getch();
}
Output
********** Run1 **********
Enter the number :64
64 = 3 + 61
64 = 5 + 59
64 = 11 + 53
64 = 17 + 47
64 = 23 + 41
64 can be expressed as sum of two prime numbers.
********** Run2 **********
Enter the number :11
11 can not be expressed as sum of two prime numbers.