用C语言编写程序,检查一个数是否可以表示为两个素数之和。我得到了重复的结果

用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) {

我用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;
}

我做了C++中的代码,如果你不熟悉它,它只与竞争代码很相似。 你的逻辑不好,你可能会被超过时间限制。而是这样做:

将所有素数存储在手之前,您可以在Ox*sqrtx时间内完成此操作, 然后使用set来确定这个数字是否存在于已经创建的素数集中,可以在Ologn时间内完成。 如果你在理解上有困难,请阅读

而且它也适用于4:P

Enter your number: 4
The sum of 2 and 2 is 4
#include<bits/stdc++.h>
using namespace std;
set<int> primes;
int main()
{
    int i,j,x;
    cout<<"Enter your number: ";
    cin>>x;
    //Store all the primes before hand
    for(i = 2; i<x; i++)
    {
        int square_root = sqrt(i);
        for(j=2;j<=square_root;j++)
        {
            if(i%j==0)
                break;
        }
        if(j > square_root) // j == (square_root + 1) i.e the loop never broke or it never found a number which could divide it hence i is a prime.
        {
            primes.insert(i);
        }
    }

    //Now find whether it comprises of two primes or not
    for (i=2; i<=x/2 ;i++)
    {
        if(primes.find(i) != primes.end() && primes.find(x-i) != primes.end()) 
        {
            cout<<"The sum of "<<i<<" and "<<(x-i)<<" is "<<x<<endl;
        }
    }
}
Enter your number: 16
The sum of 3 and 13 is 16
The sum of 5 and 11 is 16
Enter your number: 4
The sum of 2 and 2 is 4