给定一个随机函数rand(),可产生1~n间的随机数,如何使用它来构造一个区间在1~x间的随机函数.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int n = 11;
int randn()
{
return 1 + rand()%n;
}
int randx(int x)
{
int random;
if(x <= n)
{
while((random = randn()) > x);
}
else
{
while((random = n*(randx(1+x/n) - 1) + randn()) > x);
}
return random;
}
int main()
{
int x;
int arr[100] = {0};
scanf("%d %d",&n,&x);
srand((int)time(0));
for(int i=0; i<100000; i++)
{
arr[randx(x)-1]++;
}
for(int i=0; i<x; i++)
{
printf("%d: %d\n",i+1,arr[i]);
}
}