Code:
/* This is a free program, you can modify or redistribute it under the terms of GNU * Description: Specifies a random number generator, such as 1000, random numbers between 1 and 1000 are required, and the probability of any number between 1 and 1000 is equal, all of which are 1/1000 * language: C ++ * Development Environment: vc6.0 * Author: wangzhicheng * E-mail: 2363702560@qq.com * Date: 2012/10/5 */# include <iostream> # include <ctime> # include <cstdlib> using namespace STD; # define Max 1e10typedef long type; Template <class Type> class randomproducer {PRIVATE: type * n; type * random; void setn (type num) {* n = num;} type getn () const {return * n ;} void setrandom (type R = 0) {* random = r;} type getrandom () {return * random;} void producer () {srand (unsigned (time (0); Type I; type k = 1; for (I = 1; I <= getn (); I ++) {If (RAND () % K = 0) setrandom (I); k ++;}/* If the final result is 1, it must be 1st times, 2nd times ,... generation 1 for n times, Generation 1 for AI = {Generation 1 for I}, I = 1, 2 ,... n. P (an) = P (a1a2a3... an) = P (A1) * P (A2 | A1) * P (A3 | a1a2 )*... * P (an | A1A2...AN-1) = 1 * (1/2) * (2/3) * (3/4 )*... (N-1)/n) = 1/N and so on, so according to the above method, the probability of generating any number between 1 and 1000 is 1/N */} public: randomproducer (type num) {If (Num <= 0 | num> = max) {cerr <"the input data must be greater than 0 and less than" <max <Endl; cerr <"program exited! "<Endl; exit (1);} n = new type; setn (Num); random = new type; setrandom (0); Producer ();}~ Randomproducer () {Delete N; n = 0; Delete random; random = 0;} void show () const {cout <"generates a random number: "<* random <Endl ;}; void main () {cout <" written by wangzhicheng, copyright (c) 2012/10/5 "<Endl; Type N; cout <"enter an integer greater than 0 and less than" <Max; cout <":"; CIN> N; If (! Cin. Good () {cerr <"the input format is invalid. The program exits! "<Endl; exit (1);} randomproducer <type> instance (n); instance. Show ();}
Test: