How to generate a very large random number in C ++

I want to generate a very large random number in the range 0 - 2 ^ 64 using C ++. I used the rand () function, but it does not generate a very large number. Can anyone help?

+4
source share
5 answers

With C ++ 11, using the standard C ++ 11 random library , you can do this:

#include <iostream>
#include <random>

int main()
{
  /* Seed */
  std::random_device rd;

  /* Random number generator */
  std::default_random_engine generator(rd());

  /* Distribution on which to apply the generator */
  std::uniform_int_distribution<long long unsigned> distribution(0,0xFFFFFFFFFFFFFFFF);

  for (int i = 0; i < 10; i++) {
      std::cout << distribution(generator) << std::endl;
  }

  return 0;
}

Live Demo

+9
source

Since the uniformly random number in the range [0, 2^64)is only 64 random bits, you can simply use the return values std::mt19937_64directly:

#include <random>

int main () {
    std::mt19937_64 gen (std::random_device{}());

    std::uint64_t randomNumber = gen();
}

, Mersenne Twister 32- , this.

, rand . - . .

+5

. , . Linux getrandom(). Windows CryptGenRandom. OpenBSD arc4random. iOS SecRandomCopyBytes. .. ..

+1

, 19- . rand(). 19- , , .

unsigned long long Randomize()
{
    unsigned long long randnumber = 0;
    int digits[20];

    for (int i = 19; i >= 1; i--)
    {
      digits[i]=rand()%10:
    }
    for(int i=19; i>=1; i--)
    {
       unsigned long long power = pow(10, i-1);

        if (power%2 != 0 && power != 1)     //eliminates "bug" (which comes from long long power is not a float))
            power++;

        randnumber += power * digits[i];
    }
return randnumber;
}

,

#include <stdlib.h>
#include <time.h>
#include <math.h>

:

srand(time(NULL));
randomnumber = Randomize()%10000000+10000000;

- 10000000 20000000.

+1

rand() [0, 2^15), 5 , rand(), [0, 2^64).

, ( ). rand() ++ . , .

, 64- :

unsigned long long rand64()
{
    static unsigned long long seed;
    seed = seed * 6364136223846793005 + 1442695040888963407;
    return seed;
}

6364136223846793005 1442695040888963407 - , .

. , .

-3
source

All Articles