Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
C program for a number to be expressed as a sum of two prime numbers.
In C, we can check if a given positive integer can be expressed as the sum of two prime numbers. This concept is related to Goldbach's conjecture, which states that every even integer greater than 2 can be expressed as the sum of two primes.
Syntax
int isPrime(int n); // Returns 1 if n is prime, 0 otherwise
Algorithm
The algorithm to check if a number can be expressed as sum of two primes is −
- Step 1: Input the number to be checked
- Step 2: Iterate from i = 2 to (num/2)
- Step 3: Check if i is a prime number
- Step 4: If i is prime, check if (num - i) is also prime
- Step 5: If both i and (num - i) are primes, the number can be expressed as their sum
Example
The following C program checks if a given number can be expressed as the sum of two prime numbers −
#include <stdio.h>
int isPrime(int n) {
if (n <= 1) return 0;
if (n == 2) return 1;
if (n % 2 == 0) return 0;
for (int i = 3; i * i <= n; i += 2) {
if (n % i == 0) {
return 0;
}
}
return 1;
}
int main() {
int num = 34;
int flag = 0;
printf("Number: %d<br>", num);
printf("Prime pairs that sum to %d:<br>", num);
for (int i = 2; i <= num/2; i++) {
if (isPrime(i) && isPrime(num - i)) {
printf("%d + %d = %d<br>", i, num - i, num);
flag = 1;
}
}
if (flag == 0) {
printf("The number %d cannot be expressed as sum of two primes<br>", num);
}
return 0;
}
Number: 34 Prime pairs that sum to 34: 3 + 31 = 34 5 + 29 = 34 11 + 23 = 34 17 + 17 = 34
Key Points
- The
isPrime()function efficiently checks primality by testing divisibility up to ?n - We only check up to
num/2to avoid duplicate pairs (e.g., 3+31 and 31+3) - Even numbers greater than 2 usually have multiple prime pair representations
- Odd numbers can only be expressed as sum of two primes if one of them is 2
Conclusion
This program demonstrates how to find all possible ways to express a number as the sum of two prime numbers. The algorithm uses an efficient prime checking function and iterates through potential pairs systematically.
Advertisements
