228k views
12 votes
Generate random numbers in any language, calculate the time complexity , but do not use any library while doing this.

User Crysfel
by
3.3k points

1 Answer

3 votes

Answer:

There are many pseudorandom number generation algorithms.

Here is a simple one.

(1) Choose the seed value seed and assign it to x. Variable x will store generated random numbers one at a time.

(2) Calculate a random number as follows

x=(a⋅x+c) mod m .

Here a, and c are some constants. c, and seed should be in the range [0, m] and a in [1, m]. m should be a big number, it defines the range of generated random numbers.

(3) To produce random numbers in [0, m-1], repeat step (2) as many times as necessary.

We have a working algorithm now, the problem however that it will generate the same sequence of random numbers, unless we change the seed value. So every time you invoke this algorithm, the seed have to be changed. The only quantity that is always changing in a deterministic computer is time. Hence, using current time as a seed value will produce different sequences of numbers.

Here is a complete example in C that generates 5 random numbers in the range [0, 32767]

Step-by-step explanation:

#include <stdio.h>

#include <time.h>

unsigned long int x = 1;

unsigned long _rand(){

unsigned long a = 950213;

unsigned long c = 12345;

unsigned long m = 32768;

x = x * a + c;

return (unsigned long) (x >> 16) % m;

}

void _srand(unsigned long seed){

x = seed;

}

int main(){

int i;

_srand(time(NULL));

for(i = 0; i < 5; i++)

printf("%ld\\", _rand());

}

#◌⑅⃝●♡⋆♡Nåmřāthā ♡⋆♡●⑅◌

User Adam Bronfin
by
3.8k points