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 狗狗上厕所训练
13 植物种植祝福语简短
14 翻译考试祝福语朋友简短
15 个人周年庆简短祝福语
16 狗狗怎么训练
17 分别祝福语简短搞笑英文
18 生日广州男生祝福语简短