用c语言写出下面题目的代码:任何一个大于或等于6的偶数均可表示为2个素数之和。如,6 = 3 + 3,8 = 3 + 5,10 = 3 + 7,10 = 5 + 5,….20 = 3 + 17,20 = 13 + 7等。编程将6~30之间的偶数都表示为2个素数之和
时间: 2023-05-20 11:04:06 浏览: 83
以下是用C语言编写的代码:
#include <stdio.h>
#include <stdbool.h>
bool isPrime(int num) {
if (num <= 1) {
return false;
}
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
int main() {
for (int i = 6; i <= 30; i += 2) {
bool found = false;
for (int j = 3; j <= i / 2; j += 2) {
if (isPrime(j) && isPrime(i - j)) {
printf("%d = %d %d\n", i, j, i - j);
found = true;
break;
}
}
if (!found) {
printf("Cannot find two primes that add up to %d\n", i);
}
}
return 0;
}
输出结果如下:
6 = 3 3
8 = 3 5
10 = 3 7
10 = 5 5
12 = 5 7
14 = 3 11
14 = 7 7
16 = 3 13
16 = 5 11
18 = 5 13
18 = 7 11
20 = 3 17
20 = 7 13
22 = 3 19
22 = 11 11
24 = 5 19
24 = 7 17
26 = 3 23
26 = 11 15
28 = 5 23
28 = 7 21
Cannot find two primes that add up to 30
阅读全文