View Javadoc
1   /*
2    * License : The MIT License
3    * Copyright(c) 2022 olyutorskii
4    */
5   
6   package io.github.olyutorskii.aletojio.rng.lcg;
7   
8   import io.github.olyutorskii.aletojio.rng.RndInt31;
9   
10  /**
11   * Implementation of 31bit output Linear congruential generator(LCG).
12   *
13   * <p>LCG is a commonly used random number generator in the past.
14   *
15   * <p>* LCG implementations on CPU without 64-bit remainders
16   * often output only 31-bit random numbers.
17   *
18   * <p>Recurrence relation sequences : {@code X(n+1) = (X(n) * Mul + Inc) mod Mod}
19   *
20   * <ul>
21   * <li>Mul : Multiplier
22   * <li>Inc : Increment
23   * <li>Mod : Modulus
24   * </ul>
25   *
26   * @see <a href="https://en.wikipedia.org/wiki/Linear_congruential_generator">
27   * Linear congruential generator (Wikipedia)
28   * </a>
29   */
30  public class LcgRndInt31 extends AbstractLcg implements RndInt31 {
31  
32      /**
33       * Constructor.
34       *
35       * <ul>
36       * <li>Multiplier must be 1 or greatrer.
37       * <li>Increment must be 0 or greatrer.
38       * <li>Modulus must be 2 or greater.
39       * </ul>
40       *
41       * @param mulArg multiplier
42       * @param incArg increment
43       * @param modArg modulus
44       * @throws IllegalArgumentException illegal argument
45       */
46      public LcgRndInt31(long mulArg, long incArg, long modArg)
47              throws IllegalArgumentException {
48          super(mulArg, incArg, modArg);
49          return;
50      }
51  
52      /**
53       * {@inheritDoc}
54       *
55       * <p>result(31bit) reflects seed[0:30]
56       *
57       * @return {@inheritDoc}
58       */
59      @Override
60      protected int seedToResult() {
61          long lVal = getSeed() & MASK_B31;
62          int result = (int) lVal;
63          return result;
64      }
65  
66      /**
67       * {@inheritDoc}
68       *
69       * @return {@inheritDoc}
70       */
71      @Override
72      public int nextInt31() {
73          int result = nextIntImpl();
74          return result;
75      }
76  
77  }