The output m of a random equal probability in C++,1....N (assuming N is much larger than m).

Source: Internet
Author: User

# 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).

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.