求差值最小的素数之和,

可以从该数的半值开始向两端检索素数情况。

有效减少循环次数。


关于素数的判定:

求某数的平方根,然后用该数除以2到平方根,如果都不能整除,则为素数。

原因是如果某数m能被2~m-1中间的某一个整数整除,

那么其因子必定一个大于等于根号m,一个小于等于根号m,

所以在2~根号m的范围内必定能寻找到其中一个因子(如果有)。

因而根号m之后的值不必再遍历。

有效减少循环次数。


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

int N;
int mid;
int i;
int j;
int x,y;


int judge_sushu(int celement)
{
    int n;
    int k;
   
    k=(int)sqrt(celement);
    
        for(n=2;n<=k;n++)//if number m can be aliquot(zhengchu) by the number from 2 to m-1,
                         //its two factors(yinzi) must one lagerer than sqrt root m, another
                        // one smaller than sqrt m.
        {
            if(celement%n==0)//be aliquot, jump out of the loop
            {
                break;
            }
        }
    
    if(n>k)//if it is not a prime number(sushu), the loop will be ended earlier
           //if it is a prime number,the times of the loop will be k+1.
        {
            return 1;
        }
    else
        {
            return 0;
        }

}


int main()
{
    scanf("%d\n",&N);
    
    mid =N/2;
    //从中间开始向两端检索加和等于n的数字组合,然后分别判断是否均为素数,如果是,则break;
    for(i=mid,j=mid;(i>=1)&&(j<N);i--,j++)
    {
       x=judge_sushu(i);
       y=judge_sushu(j);
        if((x&&y)==1)
        {
           printf("%d\n",i);
           printf("%d\n",j) ;
           break;
        }
    }
    
    
    
}