Search code examples
pythonpython-3.xcryptographypseudocodelcg

Unable to understand the code for linear congruential generator


I am making another python script to perform linear congruential generator to generate 55 pseudo-random number but having trouble understanding the algorithm of linear congruential generator and how does my scripts work even though the script is simple for me to write.

Based on the python script, why is the output is changing in every loop? Is the python script correct for the linear congruential generator?

#!/usr/bin/python3
# Fix variable for the seed, modulus, a and c 
seed = 8 
a = 2
c = 2 
m = 20

# counter for how many iterations we've run
counter = 0
#Perfom number of iterations requested by user
while counter < 50:
    # Store value of each iteration
    seed = (a * seed + c) % m
    counter = counter + 1

Solution

  • The output is changing on every iteration due to the seed variable being updated, your using the seed from the previous iteration to change the seed of the next iteration.

    seed = (a * seed + c) % m

    On the first iteration your seed is 5, so

    (3 * 5 + 3) % 19

    gives 18. On the second iteration

    (3 * 18 + 3) % 19

    gives 0, because 3*18 + 3 is 57 and 57 modulus m which is 19 is 0. and so the loop continues, with each previous seed impacting the next.