# C 程序：检查一个数字是否可以表示为两个质数之和

> 原文： [https://www.programiz.com/c-programming/examples/sum-prime-numbers](https://www.programiz.com/c-programming/examples/sum-prime-numbers)

#### 在此示例中，您将学习检查用户输入的整数是否可以表示为所有可能组合的两个质数之和。

要理解此示例，您应该了解以下 [C 编程](/c-programming "C tutorial")主题：

*   [C `if...else`语句](/c-programming/c-if-else-statement)
*   [C `for`循环](/c-programming/c-for-loop)
*   [C 函数](/c-programming/c-functions)
*   [C 用户定义的函数](/c-programming/c-user-defined-functions)

* * *

为了完成此任务，我们将创建一个名为`checkPrime()`的函数。

如果传递给函数的数字是[质数](https://www.programiz.com/c-programming/examples/prime-number)，则`checkPrime()`返回 1。

* * *

## 作为两个质数之和的整数

```c
#include <stdio.h>
int checkPrime(int n);
int main() {
    int n, i, flag = 0;
    printf("Enter a positive integer: ");
    scanf("%d", &n);

    for (i = 2; i <= n / 2; ++i) {
        // condition for i to be a prime number
        if (checkPrime(i) == 1) {
            // condition for n-i to be a prime number
            if (checkPrime(n - i) == 1) {
                printf("%d = %d + %d\n", n, i, n - i);
                flag = 1;
            }
        }
    }
    if (flag == 0)
        printf("%d cannot be expressed as the sum of two prime numbers.", n);

    return 0;
}

// function to check prime number
int checkPrime(int n) {
    int i, isPrime = 1;
    for (i = 2; i <= n / 2; ++i) {
        if (n % i == 0) {
            isPrime = 0;
            break;
        }
    }
    return isPrime;
} 
```

**输出**

```c
Enter a positive integer: 34
34 = 3 + 31
34 = 5 + 29
34 = 11 + 23
34 = 17 + 17 
```