C语言,把一个大于4的偶数分成两个质数之和,这段程序错哪了?

2025-04-05 11:48:12
推荐回答(3个)
回答1:


//初始化没做好啊

#include
#include
int main()
{
int flag_a=0,flag_b=0,num;
int a=3,b,i,j,k;
for(k=1;k<=100;k++)
{
        
    printf("Please int put an even number(more than 4): \n");
    scanf("%d",&num);
        if(num%2!=0 || num<=4) continue;
    a=3;//Note:here
        while(a<=num/2)
    {
            flag_a=0;//Note:here
        for(i=3;i*i<=a;i=i+2)
        {
                if(a%i==0)break;
            }
        if(i*i>a)flag_a=1;

            
            flag_b=0;//Note:here
            b=num-a;
            for(j=3;j*j<=b;j=j+2)
        {
                if(b%j==0)break;
            }
        if(j*j>b)flag_b=1;
        if(flag_a==1 && flag_b==1)break;
            a+=2;
    }
        printf("%d=%d+%d\n",num,a,b);
}
}

回答2:

首先你的求素数有问题,其次int a=3,应放在循环体里面。
求素数应该单写一个函数,有利于代码复用。
给赞哦!!!
#include
#include
int plain(int n)
{
int i=2;
int result=0;
for(i=2;i*i<=n;i++)
if(n%i==0)
break;
if(i*i>n)
result=1;
return result;
}
int main()
{
int flag_a=0, flag_b=0,num;
int a,b,i,j,k;
for(k=1;k<=100;k++)
{ a=3; //应该在此处
printf("Please int put an even number(more than 4): \n");
scanf("%d",&num);
while(a<=num/2)
{
b=num-a;

if(plain(a)&&plain(b))
printf("%d=%d+%d\n",num,a,b);
a=a+2;
}

}
}

回答3:

算法错了吧,别问我怎么改