Exercise:
Write a C Program to check whether a number can be expressed as sum of two prime numbers.
Click Here to View the Solution!
#include <stdio.h>
int checkIntPrime(int num);
int main() {
int num, i;
int flag = 0;
printf("Enter a positive integer: ");
scanf("%d", &num);
for (i = 2; i <= num / 2; ++i) {
if (checkIntPrime(i) == 1) {
if (checkIntPrime(num - i) == 1) {
printf("%d = %d + %d\n", num, i, num - i);
flag = 1;
}
}
}
if (flag == 0)
printf("%d cannot be expressed as the sum of two prime numbers.", num);
return 0;
}
int checkIntPrime(int num) {
int i, isIntPrime = 1;
for (i = 2; i <= num / 2; ++i) {
if (num % i == 0) {
isIntPrime = 0;
break;
}
}
return isIntPrime;
}
Click Here to View the Output!
Enter a positive integer: 4
4 = 2 + 2
Click Here to View the Explanation!
- This program is used to check whether a number can expressed as a sum of two prime numbers.
- A function
checkIntPrime
is initialized. - In
main()
, the program requests the use to enter a positive integer and stores it in the variablenum
using thescanf()
function. - A
for loop
is initialized with a condition that will iterate betweeni = 2
andi <= num/2
and each timei
will be incremented. - A condition in the
if statement
will be set which will check whetheri
is a prime number. And anotherif statement
to check whethernum-i
is a prime number. - If both
if statements
will be true, i andnum-i
will be added to check if their sum is equal tonum
and theflag
will be set to 1. - If the
flag
will be 0, a message will be printed that the number cannot be expressed as a sum of two prime numbers. - The
function checkIntPrime
is created at the end which will check whethernum
is exactly divisible byi
, if true, the variableisPrime
will be set to 0 else will remain 1 and will be returned.