Skip to content

Instantly share code, notes, and snippets.

@colomon
Created September 24, 2012 02:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save colomon/3773886 to your computer and use it in GitHub Desktop.
Save colomon/3773886 to your computer and use it in GitHub Desktop.
static readonly Func<Constants,Variable,Variable> bigrand_d = bigrand;
[ImplicitConsts] public static Variable bigrand(Constants c, Variable a1) {
int r1;
P6any o1 = a1.Fetch();
if (!o1.mo.is_any)
return HandleSpecial1(c, a1, o1, bigrand_d);
P6any n1 = GetNumber(a1, o1, out r1);
BigInteger top = PromoteToBigInt(r1, n1);
int bits = (int) Math.Ceiling(BigInteger.Log(top, 2));
int bytes = bits / 8 + 1;
byte mask = 0;
switch(bits % 8) {
case 0: mask = 255; break;
case 1: mask = 1; break;
case 2: mask = 3; break;
case 3: mask = 7; break;
case 4: mask = 15; break;
case 5: mask = 31; break;
case 6: mask = 63; break;
case 7: mask = 127; break;
}
Random rnd = new Random();
Byte[] b = new Byte[bytes + 1];
while (true) {
rnd.NextBytes(b);
b[bytes] = 0;
b[bytes - 1] &= mask;
BigInteger candidate = new BigInteger (b);
if (candidate < top)
return MakeInt(candidate);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment