-
Notifications
You must be signed in to change notification settings - Fork 0
/
RandomBigInteger.cs
83 lines (70 loc) · 2.7 KB
/
RandomBigInteger.cs
1
2
3
4
5
6
7
8
9
10
11
12
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace System.Numerics
{
class RandomBigInteger : Random
{
public RandomBigInteger() : base()
{
}
public RandomBigInteger(int Seed) : base(Seed)
{
}
/// <summary>
/// Generates a random positive BigInteger between 0 and 2^bitLength (non-inclusive).
/// </summary>
/// <param name="bitLength">The number of random bits to generate.</param>
/// <returns>A random positive BigInteger between 0 and 2^bitLength (non-inclusive).</returns>
public BigInteger NextBigInteger(int bitLength)
{
if (bitLength < 1) return BigInteger.Zero;
int bytes = bitLength / 8;
int bits = bitLength % 8;
// Generates enough random bytes to cover our bits.
byte[] bs = new byte[bytes + 1];
NextBytes(bs);
// Mask out the unnecessary bits.
byte mask = (byte)(0xFF >> (8 - bits));
bs[bs.Length - 1] &= mask;
return new BigInteger(bs);
}
/// <summary>
/// Generates a random BigInteger between start and end (non-inclusive).
/// </summary>
/// <param name="start">The lower bound.</param>
/// <param name="end">The upper bound (non-inclusive).</param>
/// <returns>A random BigInteger between start and end (non-inclusive)</returns>
public BigInteger NextBigInteger(BigInteger start, BigInteger end)
{
if (start == end) return start;
BigInteger res = end;
// Swap start and end if given in reverse order.
if (start > end)
{
end = start;
start = res;
res = end - start;
}
else
// The distance between start and end to generate a random BigIntger between 0 and (end-start) (non-inclusive).
res -= start;
byte[] bs = res.ToByteArray();
// Count the number of bits necessary for res.
int bits = 8;
byte mask = 0x7F;
while ((bs[bs.Length - 1] & mask) == bs[bs.Length - 1])
{
bits--;
mask >>= 1;
}
bits += 8 * bs.Length;
// Generate a random BigInteger that is the first power of 2 larger than res,
// then scale the range down to the size of res,
// finally add start back on to shift back to the desired range and return.
return ((NextBigInteger(bits + 1) * res) / BigInteger.Pow(2, bits + 1)) + start;
}
}
}