# include <stdlib.h>
# include <time.h>
Knuth (intint m) { int) time (0)); for (int0; i < n; i++) { if (rand ()% (N-i) <m) { < < I << Endl; M--; }} }
To facilitate interpretation, assume that n equals 10,m equals 5:
The remainder range of the first rand ()% (n-0) is 0~9, which is likely to be less than M (=5) and can be output i=0; then i++,m--
The remainder range of the second rand ()% (n-1) is 0~8, which is likely to be less than M (=4) and can be output i=1; then i++,m--
...
The remainder range for the fifth time rand ()% (n-4) is 0~5, which is likely to be less than M (=1), which can output i=4; then i++,m--
The remainder range of the sixth rand ()% (n-5) is 0~4 and cannot be less than M (=0), the algorithm ends
Also explain the usage of srand () and the rand () function. Srand () is the seed seed provided to Rand (), and if Srand is the same value each time it is entered, the random number generated by each run is the same. It is a disadvantage to use a fixed number as a seed, and the usual practice is to replace it with such a code Srand ((unsigned) time (0)) , which will make the seed an invariant number, so that the resulting random number will not be the same every execution. The time function is included in the time.h, using the system clock.
The output m of a random equal probability in C++,1....N (assuming N is much larger than m).