我编写了以下程序,以检查给定数字是否可以表示为两个质数之和。它可以编译,但不能按预期工作。例如,对于输入= 16,它显示16不能表示为两个质数之和。同样对于输入= 5,它显示5 = 3 + 2而不是5 = 2 + 3。

/* Program to check whether a number can be expressed as a sum of two prime numbers*/
#include <stdio.h>
#include <stdlib.h>

int prime(int x)
{
    int fact=0,i;
    for(i=2;i<x;i++)
    {
        if(x%i==0)
        {
            fact++;
            break;
        }
    }
    if (fact==0)
        return 1;
    else return 0;
}
int main()
{
    int a,b,c,d,count=0;
    printf("Enter Number\n");
    scanf("%d",&a);
    for(b=2;b<(a+1)/2;b++);
    {
        c = prime(b);
        d = prime(a-b);
        if (c==1 && d==1)
        {
            printf("%d = %d + %d\n",a,b,a-b);
            count++;
        }
    }
    if(count==0)
        {
            printf("%d cannot be expressed as sum of two prime numbers.\n",a);
        }
    return 0;
}

最佳答案

您的代码中有两个错误:

在函数prime()中,您不会在x中检查2的值,该值也是素数。

第二个错误是;语句之后的for

for(b=2;b<(a+1)/2;b++);


删除它,否则不会在每次循环迭代时执行以下块(在{}之间的部分),而是仅在循环结束之后执行。

通常,您不需要读取浮点数,而需要一个整数。在您的用例中使用fgets()atoi()。这些比scanf()安全得多。

最后一点:在运算符前后添加空格。这使代码更具可读性。

完整的代码

#include <stdio.h>
#include <stdlib.h>

int prime(int x)
{
    int i;

    if (x == 2)
    {
        return 1;
    }

    for (i = 2; i < x; i++)
    {
        if (x % i == 0)
        {
            return 0;
        }
    }

    return 1;
}

int main()
{
    int read_number;
    int summand1;
    int summand2;
    int count = 0;
    int max;
    char buffer[100];

    printf("Enter Number\n");
    fgets(buffer, sizeof(buffer), stdin);
    read_number = atoi(buffer);

    max = (read_number + 1) / 2;

    for (summand1 = 2; summand1 < max; ++summand1)
    {
        summand2 = read_number - summand1;
        if ((prime(summand1) == 1) && (prime(summand2) == 1))
        {
            printf("%d = %d + %d\n", read_number, summand1, summand2);
            count++;
        }
    }

    if (count == 0)
    {
        printf("%d cannot be expressed as sum of two prime numbers.\n", read_number);
    }

    return 0;
}


当然,您可以进行一些优化。例如,在prime()中:如果已经检查到x不是2的倍数,则可以从3开始循环,并在非常迭代的时间内将i增加2。或者,如果i大于x的平方根,则可以停止此循环。这些措施可能会加快大量代码的速度,但可能会使代码的可读性降低。这是您必须考虑的折衷方案,特别是如果您开始学习编程的话。

10-08 09:34
查看更多