-3

I know how to generate Random numbers in C++. Like,

int num = rand()%(1000)+1;

Then the random number will be between 1 to 1000. But My Questions are-

  1. How can I generate numbers between two fix range, whether the upper snippet can generate number between 1 to X. But what should I do for two different range (X to Y).Like I want to generate Random numbers between 1000 to 5000.
  1. How can I generate numbers more than 32 bit and up to 64 bit? I tried like this-

long long num = rand()%(1000000000000000000)+1;

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982

1 Answers1

0

Given integer values X, Y and you want random value between...

int range = abs(Y-X) + 1;
int randNum = rand() % (range) + X;

As for longer numbers... just add 2 random values together. So if you want a result that can be 64bits in size max then

int randNum1 = rand();
int randNum2 = rand();
long long range = abs(Y-X) + 1;
long long finalNum = (randNum1 + randNum2) % (range) + X;
DynasticSponge
  • 1,416
  • 2
  • 9
  • 13
  • 1
    Adding two uniformly distributed random numbers does not result in a uniformly distributed output. – elliptic_hyperboloid Jul 01 '20 at 17:51
  • Too true.. but using rand() at all is only pseudo-random to begin with... its generally acceptable for most purposes. If you need true randomness then you need something besides rand() – DynasticSponge Jul 01 '20 at 17:53
  • problem with `rand()` is not that it is pseudo random, but that it is pseudo random of poor quality. Also for uniform + uniform != uniform, pseudo or not isnt that relevant – 463035818_is_not_an_ai Jul 01 '20 at 17:55
  • 1
    If you are doing statistic modelling on something and need to run and compare multiple iterations against each other, then yes uniform+uniform might cause problems. But for any single given event where you just want to pick an option, such as (display random picture from a really large pool of pictures), the purpose is more just that you dont explicitly calculate next choice. For that purpose, what I have should work – DynasticSponge Jul 01 '20 at 18:02
  • @DynasticSponge doesn't adding too rand() values result in an overflow if the values are too large??? – Yunfei Chen Jul 01 '20 at 18:35
  • would depend on RAND_MAX on the system... but most implementations have settled on it returning a value that fits into a standard 32bit int. Even if it returns max int value, twice, and you add them.. You just increased the required bit size by one bit. So you could add up to 32 rand() results together and still fit in a long long – DynasticSponge Jul 01 '20 at 19:06