🔄📚Intermediate
Check if Number is Sum of Two Primes
Express number as sum of primes
Check if a number can be expressed as the sum of two prime numbers (Goldbach's conjecture).
Program Code
sum_two_primes.c
C
1#include <stdio.h>2#include <stdbool.h>34bool isPrime(int num) {5 if (num <= 1) return false;6 for (int i = 2; i * i <= num; i++) {7 if (num % i == 0) return false;8 }9 return true;10}1112int main() {13 int n;14 15 printf("Enter a positive integer: ");16 scanf("%d", &n);17 18 bool found = false;19 20 printf("%d can be expressed as:\n", n);21 22 for (int i = 2; i <= n / 2; i++) {23 if (isPrime(i) && isPrime(n - i)) {24 printf("%d = %d + %d\n", n, i, n - i);25 found = true;26 }27 }28 29 if (!found) {30 printf("Cannot be expressed as sum of two primes\n");31 }32 33 return 0;34}Output
Enter a positive integer: 34
34 can be expressed as:
34 = 3 + 31
34 = 5 + 29
34 = 11 + 23
34 = 17 + 17
Related Examples
Want to Learn More?
Explore our comprehensive tutorials for in-depth explanations of C programming concepts.
Browse Tutorials