将一个数字表示为两个素数之和的 C 程序。
问题
找出给定的数字是否可以表示为两个素数之和。
给定一个正整数 N,我们需要检查数字 N 是否可以表示为两个素数之和。
解决方案
考虑以下示例:
20 可以表示为两个素数 3 和 17 之和,13 和 7 之和。
20= 3+7
20= 13+7
算法
参考以下算法,将给定数字表示为两个素数之和。
步骤 1 - 在运行时输入要检查的数字。
步骤 2 - 从 i = 2 重复到 (num/2)。
步骤 3 - 检查 i 是否为素数。
步骤 4 - 如果 i 是素数,则检查 (n - i) 是否为素数。
步骤 5 - 如果 (i) 和 (n - i) 都是素数,则给定数字可以表示为素数 i 和 (n - i) 的和。
示例
以下是将给定数字表示为两个素数之和的 C 程序:
#include <stdio.h>
int Sum(int n);
int main(){
int num, i;
printf("Enter number: ");
scanf("%d", &num);
int flag = 0;
for(i = 2; i <= num/2; ++i){
if (sum(i) == 1){
if (sum(num-i) == 1){
printf("
The given %d can be expressed as the sum of %d and %d
", num, i, num - i);
flag = 1;
}
}
}
if (flag == 0)
printf("The given %d cannot be expressed as the sum of two prime numbers
", num);
return 0;
}
//check if a number is prime or not
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: Enter number: 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: Enter number: 11 The given 11 cannot be expressed as the sum of two prime numbers
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP