Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate very Large random number in c++

Tags:

c++

I want to generate very large random number in range of 0 - 2^64 using c++. I have used the rand() function but it is not generating very large number. Can any one help?

like image 711
Nabeel_Afzal Avatar asked May 23 '16 16:05

Nabeel_Afzal


People also ask

How do you generate a random number in C?

For random number generator in C, we use rand() and srand() functions that can generate the same and different random numbers on execution.

How do you generate a random number between 1 and 10 in C?

In this program we call the srand () function with the system clock, to initiate the process of generating random numbers. And the rand () function is called with module 10 operator to generate the random numbers between 1 to 10. srand(time(0)); // Initialize random number generator.

How do I generate a 32 bit random number in C++?

The answer is simple: use std::random_device to generate a single random number which is then used as a seed for a pseudorandom number generator (PRNG) and then use the PRNG itself to generate as many pseudorandom numbers as we wish.

What library is rand () in C?

1.1. The rand function, declared in stdlib. h, returns a random integer in the range 0 to RAND_MAX (inclusive) every time you call it. On machines using the GNU C library RAND_MAX is equal to INT_MAX or 231-1, but it may be as small as 32767.


1 Answers

With c++11, using the standard random library of c++11, 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

like image 83
coyotte508 Avatar answered Sep 23 '22 06:09

coyotte508