我用c编写了以下代码
/* Function to check whether the number is prime or composite*/
int prime(int a)
{
int i;
int count=0;
for(i=1;i<a;i++)
{
if (a%i==0)
{
count+=1;
}
}
if (a<=1)
{
return 0;
}
else if (count>1)
{
return 1;
}
else
{
return 2;
}
}
/* Code for the main function*/
int main()
{
printf("Enter your desired number");
int a;
scanf("%d",&a);
int i;
for(i=2;i<a;i++)
{
if (prime(i)==2 && prime(a-i)==2)
{
printf("The sum of %d and %d is %d\n",i,a-i,a);
}
}
return 0;
}
我遇到的问题是数字 16 的结果如下: 3 和 13 的和是 16 5 和 11 的和是 16 11 和 5 的和是 16 13 和 3 的和是 16 我不想再重蹈覆辙。请帮忙
最佳答案
到达一半时停止。所有因子在中间点之后将是对称的。
#include <stdio.h>
int prime(int a)
{
int i;
int count=0;
for(i=1;i<a;i++)
{
if (a%i==0)
{
count+=1;
}
}
if (a<=1)
{
return 0;
}
else if (count>1)
{
return 1;
}
else
{
return 2;
}
}
int main()
{
printf("Enter your desired number");
int a;
scanf("%d",&a);
int i;
for(i=2;i<(a/2);i++)
{
if (prime(i)==2 && prime(a-i)==2)
{
printf("The sum of %d and %d is %d\n",i,a-i,a);
}
}
return 0;
}
输出:
Enter your desired number16
The sum of 3 and 13 is 16
The sum of 5 and 11 is 16
关于c - 用 C 编写程序来检查一个数字是否可以表示为两个素数之和。我得到重复的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46621212/