C 程序将一个数表示为两个素数之和。
问题
找出给定的数字是否可以表示为两个素数之和。
给定一个正整数N,我们需要检查数字N是否可以表示为两个素数之和。
解决方案
考虑下面给出的例子-
20可以表示为两个素数3和17、13和7的和。
20=3+7
20=13+7
算法
参考下面给出的将给定数字表示为两个素数之和的算法。
步骤1-输入要在运行时检查的数字。
步骤2-从i=2重复到(num/2)。
步骤3-检查i是素数。
Step4-如果i是素数,检查(n-i)是否是素数。
步骤5-如果(i)和(n-i)都是素数,则给定的数字可以表示为素数i和(n-i)的总和。
示例
以下是将给定数字表示为两个素数之和的C程序-
#include输出结果int Sum(int n); int main(){ int num, i; printf("输入号码: "); scanf("%d", &num); int flag = 0; for(i = 2; i <= num/2; ++i){ if (sum(i) == 1){ if (sum(num-i) == 1){ printf("\nThe given %d can be expressed as the sum of %d and %d\n\n", num, i, num - i); flag = 1; } } } if (flag == 0) printf("The given %d cannot be expressed as the sum of two prime numbers\n", num); return 0; } //检查一个数是否为素数 int sum(int n){ int i, isPrime = 1; for(i = 2; i <= n/2; ++i){ if(n % i == 0){ isPrime = 0; break; } } return isPrime; }
执行上述程序时,它会产生以下输出-
Run 1: 输入号码: 34 The given 34 can be expressed as the sum of 3 and 31 The given 34 can be expressed as the sum of 5 and 29 The given 34 can be expressed as the sum of 11 and 23 The given 34 can be expressed as the sum of 17 and 17 Run 2: 输入号码: 11 The given 11 cannot be expressed as the sum of two prime numbers
热门推荐
10 诗词送行祝福语大全简短
11 新房开工吉日祝福语简短
12 50多岁生日简短祝福语
13 安徽疫情祝福语简短英语
14 农民朋友发财祝福语简短
15 对生活祝福语简短精辟
16 搬家词简短祝福语朋友
17 女神结婚快乐祝福语简短
18 文学短句祝福语大全简短