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

后端 未结 3 610
南方客
南方客 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:15

    You can not have completely unrelated (particularly if you want the reverse as well).

    There is a concept of modulo inverse of a number, but this would work only if the range number is a prime, eg. 100 will not work, you would need 101 (a prime). This can provide you a pseudo random number if you want.

    Here is the concept of modulo inverse:

    If there are two numbers a and b, such that

    (a * b) % p = 1
    

    where p is any number, then

    a and b are modular inverses of each other.
    

    For this to be true, if we have to find the modular inverse of a wrt a number p, then a and p must be co-prime, ie. gcd(a,p) = 1

    So, for all numbers in a range to have modular inverses, the range bound must be a prime number.

    A few outputs for range bound 101 will be:

    1 == 1
    2 == 51
    3 == 34
    4 == 76
    etc.
    

    EDIT:

    Hey...actually you know, you can use the combined approach of modulo inverse and the method as defined by @Paul. Since every pair will be unique and all numbers will be covered, your random number can be:

    random(k) = randomUniqueNumber(ModuloInverse(k), p)      //this is Paul's function
    

提交回复
热议问题