Given a number, produce another random number that is the same every time and distinct from all other results

后端 未结 3 612
南方客
南方客 2020-11-30 15:24

Basically, I would like help designing an algorithm that takes a given number, and returns a random number that is unrelated to the first number. The stipulations being that

3条回答
  •  难免孤独
    2020-11-30 16:11

    This sounds like a non-repeating random number generator. There are several possible approaches to this.

    As described in this article, we can generate them by selecting a prime number p and satisfies p % 4 = 3 that is large enough (greater than the maximum value in the output range) and generate them this way:

    int randomNumberUnique(int range_len , int p , int x)
        if(x * 2 < p)
           return (x * x) % p
        else
           return p - (x * x) % p
    

    This algorithm will cover all values in [0 , p) for an input in range [0 , p).

提交回复
热议问题