当前位置导航:炫浪网>>网络学院>>编程开发>>C++教程>>C++进阶与实例

鬼谷子 猜数问题解决代码

这个问题的答案是13和4,原理我这里先不解释,先贴一段解决这个问题的代码 ,如下所示:

 void Guess()

{

int Num = 100;
 int y = 0;
 BOOL find = FALSE;
 int *PrimeBuffer = new int[100];
 memset(PrimeBuffer, 0 , sizeof(int) * 100);
 int *PrimeNum = new int[100];
 memset(PrimeNum,0, sizeof(int) * 100);
 int *Sum = new int[200];
 memset(Sum ,  0, sizeof(int) * 200);
 int index = 1;
 PrimeNum[0] = 2;
 PrimeBuffer[2] = 1;
 //TRACE(\"2\\n\");
 for(int i = 3 ; i < Num; i++)
 {
  find = FALSE;
  y  = (int)sqrt((double)i);
  for(int j = 2; j <= y; j++)
  {
   if(i % j == 0)
   {
    find = TRUE;
    break;
   }
  }
  if(!find)
  {
   //TRACE(\"%d\\n\",i);
   PrimeNum[index++] = i;
   PrimeBuffer[i] = 1;
  }
 }
 //TRACE(\"%\\n\\n\");
 for(int k = 0; k < index - 1 ; k++)
 {
  for(int m = k + 1 ; m < index ; m++)
  {
   Sum[PrimeNum[k] + PrimeNum[m]] = 1;
  }
 }


 BOOL bCanKeep = FALSE;
 for(k = 7 ; k < 198; k++)
 {
  if(!Sum[k])
  {
   int step = 0;
   int controller = 0;
   if(k % 2)
   {
    controller = (k - 1) / 2;
    if(k > 99)
    {
     step = (99 - 2) - (controller + 1) + 1;
    }
    else
    {
     step = (k - 2) - (controller + 1) + 1;
    }
    if(step <= 0)
     step = 1;
   }
   else
   {
    controller = (k - 2)  / 2;
    if(k > 99)
    {
     step = (99 - 2) - (controller + 2) + 1;
    }
    else
    {
     step = (k - 2) - (controller + 2) + 1;
    }
    if(step <= 0)
     step = 1;
   }

   for(int n = controller; step > 0; n--, step--)
   {
    int remain = k - n;[Page]
    if(PrimeBuffer[n] == 1) // at least the first one is prime num
    {
     if(PrimeBuffer[remain] == 1)
     {
      MessageBox(\"error\");
      delete PrimeNum;
      delete PrimeBuffer;
      delete Sum;
      return;
     }
     else//indicate the remain is a compound num,try to split it
     {
      //just here I will company my girl friend  to do some business
      for(int iter = 2; iter < remain / 2 + 1; iter++)
      {
       if(remain % iter == 0)
       {
        if(n * iter < 99)
        {
         bCanKeep = TRUE;
         break;
        }
        else
        {
         bCanKeep = FALSE;
         //Sum[k] = 0;
         break;
        }
       }
      }//end for

     }//end if
    }//end if
    else// the first one is compound num now check the second num
    {
     if(PrimeBuffer[remain] == 1)
     {
      for(int iter = 2; iter < n / 2 + 1; iter++)
      {
       if(n % iter == 0)

 

共3页 首页 上一页 1 2 3 下一页 尾页 跳转到
相关内容
赞助商链接