How to create random number generator function?

How to create our own random number generator (within a given range) function without using any inbuilt random generator functions like rand(), srand(), etc. ?
(in C++)

Hi @m_vaidya

We can do this without using any random number generator functions in C, using dynamic memory allocation. Take a look at this code, this will print 10 random numbers

#include<stdio.h>
#include<stdlib.h>
int main()
{
for(int i = 0; i< 10; i++)
{
int *p;
p = (int*)malloc(sizeof(int)); // (definition is lying under the code)
printf(“%d\n”,p);
}
return 0;
}

take a look at this blog on medium which describes this in much detail
Random Number Generation

1 Like

I wouldn’t recommend that. Doing a sloppy job with random numbers can backfire and Playstation3 was hacked because of this: Console Hacking 2010 - PS3 Epic Fail - Part 3 - YouTube

Depending on the system and C library implementation, addresses returned by malloc may be predictable. Or kinda randomish, but only a little bit. Yes, modern systems now implement address space layout randomization for security reasons, but some implementations of it are weak and don’t offer enough randomness.

It’s possible to copy/paste and use any half-decent PRNG implementation and there are many of them available. They typically provide rand and srand replacements. The choice of a seed for srand is important too. Using system time as a seed is good enough for competitive programming, but real software may need something better.

3 Likes