Question: I want to generate random numbers manually. I know that every language have the rand or random function, but I'm curious to know how this is working.
Does anyone have code for that?

Answer: 
POSIX.1-2001 gives the following example of an implementation of `rand()` and `srand()`, possibly useful when one needs the same sequence on two different machines.

```
static unsigned long next = 1;
/* RAND_MAX assumed to be 32767 */
int myrand(void) {
    next = next * 1103515245 + 12345;
    return((unsigned)(next/65536) % 32768);
}
void mysrand(unsigned seed) {
    next = seed;
}

```
The [Mersenne twister](http://en.wikipedia.org/wiki/Mersenne_twister) has a very long period (2^19937-1).

Here's a very basic implementation in C++:

```
struct MT{
    unsigned int *mt, k, g;
    ~MT(){ delete mt; }
    MT(unsigned int seed) : mt(new unsigned int[624]), k(0), g(0){
        for (int i=0; i<624; i++)
            mt[i]=!i?seed:(1812433253U*(mt[i-1]^(mt[i-1]>>30))+i);
    }
    unsigned int operator()(){
        unsigned int q=(mt[k]&0x80000000U)|(mt[(k+1)%624]&0x7fffffffU);
        mt[k]=mt[(k+397)%624]^(q>>1)^((q&1)?0x9908b0dfU:0);
        unsigned int y = mt[k];
        y ^= (y >> 11);
        y ^= (y << 7) & 0x9d2c5680U;
        y ^= (y << 15) & 0xefc60000U;
        y ^= (y >> 18);
        k = (k+1)%624;
        return y;
    }
};

```