Method of exhaustion-Han Xin dianbing and Han Xin dianbing
Han Xin dianbing.
Han Xin had a team of soldiers. He wanted to know how many people there were, so he asked the soldiers to report in line.
From 1 to 5, the number of the last soldiers reported is 1;
From 1 to 6, the number of the last soldiers reported is 5;
From 1 to 7, the last number of soldiers reported is 4;
From 1 to 11, the last number of soldiers reported is 10.
You know Han XinAt leastHow many troops are there?
2. [algorithm IDEA]
If the number of troops is set to x, the question x should satisfy the following relationship: x % 5 = 1 & x % 6 = 5 & x % 7 = 4 & x % 11 = 10
Use the exhaustive method to test x from 1, and obtain at least how many troops Han Xin has.
3. Code practice:
Example, set the flag "find"
# Include <stdio. h> # include "stdlib. h "int main () {int x = 1; int find = 0;/* set the flag to false */while (! Find) {if (x % 5 = 1 & x % 6 = 5 & x % 7 = 4 & x % 11 = 10) {find = 1 ;}x ++; printf ("x = % d \ n", x);} system ("pause");/* solve the problem */}
Running result: (the running result is the minimum number found from 1)
4. Other code:
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 ("minimum value is x = % d \ n", x); 10 goto end; 11} 12} 13 end:; 14 system ("pause"); 15}
Break statement Execution Code
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 ("minimum value is x = % d \ n", x); 10 break; 11} 12} 13 14 system ("pause"); 15}
The results are the same.
Expansion: Use a flag to obtain multiple solutions, for example, five solutions.
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 ("the value meeting the requirements is x = % d \ n", x); 10 f ++; 11} 12} 13 14 system ("pause "); 15}
21:26:44
By-lwb, reprinted with the source http://www.cnblogs.com/lwbjyp/p/6719892.html