Hello. Trying to make a large random number. Trying to do this:
__int64 p= 489133282872437279; __int64 s = rand() % p + 1; But for some reason, rand produces small values. This is because RAND_MAX = 32767. How can I increase it?
Hello. Trying to make a large random number. Trying to do this:
__int64 p= 489133282872437279; __int64 s = rand() % p + 1; But for some reason, rand produces small values. This is because RAND_MAX = 32767. How can I increase it?
Of course, it is better to use any library, but if this is a training program, you can implement it yourself.
The rand() method is based on the linear congruential method . The implementation of which is approximately as follows:
#define RAND_MAX 32767 static unsigned long int next = 1; int rand(void) { next = next * 1103515245 + 12345; return (unsigned int)(next/65536) % (RAND_MAX + 1); } void srand(unsigned int seed) { next = seed; } As you can see from here, changing the range is very easy: you need RAND_MAX replace RAND_MAX with your number and change the int to long long int .
But rand() rather “stupid”. If you implement it, then it is better to take a Mercene whirlwind from him better statistical stability and it is quite simple to implement.
Once upon a time I wrote this on the basis of Knut's "The Art of Programming":
class Random { public: typedef int RandomValue; Random& operator = (int seed) { X = seed; return *this; } Random(int seed = 1):X(seed){}; int operator()(int seed = 0) { const int MM = 2147483647; const int AA = 48271; const int QQ = 44488; const int RR = 3399; if (seed != 0) X = seed; X = AA*(X%QQ)-RR*(X/QQ); if (X < 0) X += MM; return X-1; } int operator()(int min, int max) { return (*this)()%(max-min) + min; } private: int X; }; class Random64 { typedef unsigned long long uint64; public: typedef uint64 RandomValue; Random64& operator = (uint64 seed) { X = seed; return *this; } Random64(uint64 seed = 0):X(seed){}; uint64 operator()(uint64 seed = uint64(-1)) { const uint64 a = 3202034522624059733ULL; const uint64 c = 1ULL; if (seed != uint64(-1)) X = seed; uint64 Y = a * X + c; X = a * Y + c; Y = (Y&0xFFFFFFFF00000000ULL) | (X >> 32); return Y; } uint64 operator()(uint64 min, uint64 max) { return (*this)()%(max-min) + min; } private: uint64 X; }; I think how to use, okay?
You can :
Use a third-party library: http://www.boost.org/doc/libs/1_49_0/doc/html/boost_random.html
To do something like this: Random get a; Random get b; And make a certain amount: a * (RAND_MAX + 1) + b;
(a * (RAND_MAX + 1) + b) % p if the resulting amount is greater than p? - xxclojureSource: https://ru.stackoverflow.com/questions/779115/
All Articles