穷举法—韩信点兵

  1. 问题描述

   韩信点兵。

韩信有一队兵,他想知道有多少人,便让士兵排队报数。

按从15报数,最末一个士兵报的数为1;

按从16报数,最末一个士兵报的数为5;

按从 17报数,最末一个士兵报的数为 4;

按从 111报数,最末一个士兵报的数为 10

你知道韩信至少有多少兵吗?


      2、【算法思想】

设兵数为x,则按题意x应满足下述关系式:x%5 ==1 && x%6==5 &&x %7==4 && x%11==10

用穷举法对x1开始试验,可得到韩信至少有多少兵。


      3、 代码实战:

穷举法,设置标志find

#include<stdio.h>
#include "stdlib.h"  
int main( )
{
int x =1;int find = 0; /*设置找到标志为假*/

  while (!find)
  {
    if (x % 5 == 1 && x % 6 == 5 && x % 7 == 4 && x % 11 == 10)
       {
        find = 1;
        }
    x++;
  printf(" x = %d
", x);}
  system("pause");   /*解决快闪问题*/
}

运行结果:(运行结果是从1—找到的最小数)

4、其他代码:

goto

 1 #include<stdio.h>
 2 #include "stdlib.h"  
 3 int main( )
 4 {
 5   int x ;
 6    for(x=1; ;x++)
 7    {   
 8    if(x % 5 == 1 && x % 6 == 5 && x % 7 == 4 && x % 11 == 10 )
 9       { printf("最小值是x= %d
 ",x);
10       goto end;
11         }
12      }
13    end:;
14  system("pause"); 
15 }

break语句执行代码

 1 #include<stdio.h>
 2 #include "stdlib.h"  
 3 int main( )
 4 {
 5   int x ;
 6    for(x=1; ;x++)
 7    {   
 8    if(x % 5 == 1 && x % 6 == 5 && x % 7 == 4 && x % 11 == 10 )
 9       { printf("最小值是x= %d
 ",x);
10         break;
11         }
12      }
13 
14  system("pause"); 
15 }

结果相同,不再赘述。

拓展:用标志,求多个解,如5个解

 1 #include<stdio.h>
 2 #include "stdlib.h"  
 3 int main( )
 4 {
 5     int x ;int f=0;
 6    for(x=1; f<5;x++)
 7    {   
 8    if(x % 5 == 1 && x % 6 == 5 && x % 7 == 4 && x % 11 == 10 )
 9       { printf("满足要求的值是x= %d
 ",x);
10         f++;
11         }
12      }
13 
14  system("pause"); 
15 }

 2017-04-16 21:26:44

by-lwb,转载注明出处http://www.cnblogs.com/lwbjyp/p/6719892.html 

原文地址:https://www.cnblogs.com/lwbjyp/p/6719892.html