How to get a larger random number from the c function rand()

前端 未结 4 1916
孤独总比滥情好
孤独总比滥情好 2021-01-19 21:19

I am in a coding environment where I only have access to some most basic c functions. #include\'ing other lib is not feasible.

In this environment, I can call rand()

4条回答
  •  抹茶落季
    2021-01-19 21:46

    static unsigned long next = 1;
    int my_rand(void) {
        next = next * 1103515245 + 12345;
        return((unsigned)(next/65536) % (RAND_MAX+1));
    }
    
    void my_srand(unsigned int seed) {
        next = seed;
    }
    

    on linux

    #define RAND_MAX    2147483647
    

    your environment RAND_MAX is probably 32767

    reference: http://en.wikipedia.org/wiki/Linear_congruential_generator

    if you are not memory constrained you can look also at http://en.wikipedia.org/wiki/Mersenne_twister the code is embeddable as like as the example above

提交回复
热议问题