0
\$\begingroup\$

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;
 }
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Jul 17, 2016 at 19:06
\$\endgroup\$
4
  • 2
    \$\begingroup\$ What do you need the random numbers for ? \$\endgroup\$ Commented Jul 17, 2016 at 22:43
  • 3
    \$\begingroup\$ "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. \$\endgroup\$ Commented Jul 18, 2016 at 7:14
  • 1
    \$\begingroup\$ The algorithm does not work correct: For instance: MinValue: 10000 and MaxValue: 10010 produces values like: 18752, 19675, .... \$\endgroup\$ Commented Jul 18, 2016 at 8:48
  • \$\begingroup\$ @JanDotNet Thanks for catching that. I used a lazy method adding MinValue to the remainder \$\endgroup\$ Commented Jul 18, 2016 at 16:15

1 Answer 1

1
\$\begingroup\$

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

answered Jul 18, 2016 at 8:38
\$\endgroup\$
1
  • \$\begingroup\$ Thanks, I've always had trouble finding the right operators in the language. \$\endgroup\$ Commented Jul 18, 2016 at 16:14

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.