简易随机数发生器

代码:

 

/*
This is a free Program, You can modify or redistribute it under the terms of GNU
*Description: 随机数发生器,指定一个数,比如1000,要求随机产生1到1000之间的
             任意数,并且1到1000之间任何一个数产生的概率是相等的,都是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 1e10

typedef 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++;
			}
			/*
			如果最终产生是1,那么必须保证第1次,第2次,...第N次都产生1,
			Ai={第i次产生1},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
			其余类推,所以按照以上方法,产生1到1000之间任意数的概率是1/N
			*/
		}
	public:
		RandomProducer(Type num) {
			if(num<=0 || num>=Max) {
				cerr<<"输入的数据必须大于0且小于"<<Max<<endl;
				cerr<<"程序退出!"<<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<<"产生的随机数是:"<<*random<<endl;
		}
};
void main() {
	cout<<"Written By Wangzhicheng,CopyRight(C) 2012/10/5  "<<endl;
	
	Type N;
	cout<<"请输入一个大于0且小于"<<Max;
	cout<<"的整数:";
    cin>>N; 
	if(!cin.good()) {
		cerr<<"输入格式非法,程序退出!"<<endl;
		exit(1);
	}
	RandomProducer<Type>instance(N);
	instance.show();
}


测试:

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值