首页 > 代码库 > Rand1 -> RandN

Rand1 -> RandN

Rand1*1   =>  uinformly distribution of 0,1      2

Rand1*2 + Rand1 => 0,1,2,3                          4

Rand1*3 + Rand2 => 0,1,2,3,4,5                     6

Rand1*4 + Rand3 => 0,1,2,3,4,5,6,7                8

...

Rand1*5 + Rand4 => 0,1,2,3,4,5,6,7,8,9          10

 

if(n==63)

63<64. 

Rand1*32  + Rand31 == Rand1*32 + Rand1*31 + Rand30....

RandN(){

if(N==1)

  return ...

 

 

int getRandN(int n){    int ret = 0;    while(true){        ret = RandN(n);        if(ret<n)            break;    }}int RandN(int n){   if(n<1)       return -1;   if(n==1)       return Rand1();   n2 = n/2;   return Rand1*n2 + RandN(n2-1);    }         

 

Rand1 -> RandN