## Random number

Hi!
How can I implement the fastest algorithm selecting the number of the appropriate range (min,max) ?

Added by: ~S.H.Bouwhuis, 2015 II 03

I use the following function.

typedef ttmath::Int<128> int4096;
typedef ttmath::UInt<128> uint4096;

// This function returns a random number in the specified range
int4096 GetRandomNumber(int4096 i4096Min, int4096 i4096Max)
{
int4096 i4096Random;
uint4096 u4096Random, u4096Span;

// Get random data
RandomizeArray((uint8 *)&u4096Random.table, sizeof(u4096Random.table));

// Get the range
if(i4096Min > i4096Max)
Swap(&i4096Min, &i4096Max);
u4096Span = i4096Max - i4096Min + 1;

// Make sure the number fits within the range
u4096Random %= u4096Span;
i4096Random = u4096Random + i4096Min;

return i4096Random;
}

The RandomizeArray function gets random data using rand_s (cryptographically secure random number) and does some extra hashing, but rand_s should be enough for you. Repeatedly calling rand_s and filling the internal ttmath::table with them will create random data for you.

The reason I use int4096 is that you want every number to be equally likely to be chosen. If your total range is too small compared to your requested range then some numbers are more likely than others.