gpt4 book ai didi

c - 用 C 编写程序来检查一个数字是否可以表示为两个素数之和。我得到重复的结果

转载 作者:行者123 更新时间:2023-11-30 14:54:33 26 4
gpt4 key购买 nike

我用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 的和是 165 和 11 的和是 1611 和 5 的和是 1613 和 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com