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

标签 c

我用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/

相关文章:

c - 返回指向结构体的指针

c - linux下使用C实现广播后获取IP地址

c - TCP连接双方同时发送时丢包

c - mpi 编译警告隐式声明

c - 如何使用 ansi c 通过 udp 发送字节数组?

c - 为 pthread 分配内存,然后 fork + execvp

c - 指针char输出说明

c - sdl_gl_setattribute 上的 sdl 应用程序段错误

java - C 到 Java 的转换

c++ - 文件 IO,处理 CRLF