Newer
Older
using System;
namespace PseudoRandomGenerator
{
/// <summary>
/// Linear Congruential Generator (LCG) for pseudo-random number generation without using the built-in Random class
/// </summary>
public class LCG
{
private long a = 1664525; // Multiplier
private long c = 1013904223; // Increment
private long m = 4294967296L; // Modulus (2^32 for a large cycle)
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
private long seed; // Current state (initialized by seed)
/// <summary>
/// Initializes the LCG with a specified seed to start sequence
/// </summary>
/// <param name="seed">Initial value for generating the sequence (e.g., DataTime.Now.Ticks)</param>
public LCG(long seed)
{
this.seed = seed;
}
/// <summary>
/// Generates the next pseudo-random number in the sequence
/// </summary>
/// <returns>A pseudo-random number based on the internal LCG algorithm</returns>
public long Next()
{
// Update the seed using the LCG-formula
seed = (a * seed + c) % m;
return seed;
}
/// <summary>
/// Generates a pseudo-random integer within a specified range (min, max)
/// </summary>
/// <param name="min">The inclusive lower bound of the random number</param>
/// <param name="max">The exclusive upper bound of the random number</param>
/// <returns>A pseudo-random integer between min and max</returns>
public long Next(int min, int max)
{
// Map the result of Next() to the specified range
return (int)(Next() % (max - min)) + min;
}
}
}