# Random number generator in C#

I don't know if it is any good. I've never done this, thus, I noticed it is kinda slow.

Can you suggest improvements? I may use it in actual software in the future.

private int secgen(int minvalue, int maxvalue)
{
Func<int, int, int, int> modular = (a, b, mod) =>
{
long rem;
Math.DivRem((long)a + (long)b, (long)mod, out rem);

if (rem < minvalue)
rem += minvalue;

return (int)rem;
};

byte[] entropyBytes = new byte[257];
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();

rng.GetBytes(entropyBytes);
int value = entropyBytes[0];
for (int i = 1; i < 257; i++)
{
value = modular(value, entropyBytes[i], maxvalue);

}

//MessageBox.Show(value.ToString());
return value;
}

• What do you need the random numbers for ? – Denis Jul 17 '16 at 22:43
• "good" has different meanings when it comes to random number generators. Uniformity, Independence, Replication, Cycle length, Speed, Memory usage, etc. Depends what you're going for. – craftworkgames Jul 18 '16 at 7:14
• The algorithm does not work correct: For instance: MinValue: 10000 and MaxValue: 10010 produces values like: 18752, 19675, .... – JanDotNet Jul 18 '16 at 8:48
• @JanDotNet Thanks for catching that. I used a lazy method adding MinValue to the remainder – looseblank Jul 18 '16 at 16:15

You may improve performance:

I would use the modulo operator instead of a function call you aren't benefiting from 100%. Math.DivRem returns a value (quotient) that you don't use. Same result:

var rem = a + b % mod;


Saves you a few unboxing operations and method call

Func<int, int, int, int> modular = (a, b, mod) =>
{
var rem = a + b % mod;

if (rem < minvalue)
rem += minvalue;

return rem;
};


Saves half the time? http://pastebin.com/XTaLCQh4

• Thanks, I've always had trouble finding the right operators in the language. – looseblank Jul 18 '16 at 16:14