C program to check whether a number can be expressed as sum of two prime numbers
In this article, you will learn how to find a given number that can be expressed as the sum of two prime numbers in the c programming language.
You should have knowledge of the following topics in c programming to understand this program:
- C functions
- C
main()
function - C
for
loop statement - C
if
condition statement
Example
30 = 11 + 19
30 = 13 + 17
Source Code
// C program to check whether a number can be expressed as the sum of two prime numbers
#include <stdio.h>
// @custom function to the value is prime or not
int IsPrimeNumber(int random_number) {
int flag = 1;
for (int i = 2; i <= random_number / 2; i++) {
if (random_number % i == 0) {
flag = 0;
break;
}
}
return flag;
}
// @driver function to call & check the expressed
// @As sum of two prime numbers
int main() {
int random_number, flag = 0;
printf("Enter a positive integer number: ");
scanf("%d", &random_number);
printf("\n");
for (int i = 2; i <= random_number / 2; i++) {
// It will check (i) to be a prime number
if (IsPrimeNumber(i) == 1) {
// It will check (random_number - 1) to be a prime number
if (IsPrimeNumber(random_number - i) == 1) {
printf("%d = %d + %d\n", random_number, i, random_number - i);
flag = 1;
}
}
}
if (flag == 0)
printf("%d can not be expressed as the sum of two prime numbers!\n", random_number);
return 0;
}
Output
Enter a positive integer number: 30
30 = 7 + 23
30 = 11 + 19
30 = 13 + 17
Explanation
In this given program, we have taken the random number 30
as input to exploit this number to check this.
Although first, we created a user-defined
function named IsPrimeNumber()
to check the values are prime or not at run time.
Then second we moved into the main()
function with loop iteration with iteration number is prime or not checked at run-time using this function IsPrimeNumber()
.
Then, it returns the series of the expressed sum of prime numbers if it finds this scenario in the iteration.