-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathExtensionMethods.cs
245 lines (209 loc) · 7.17 KB
/
ExtensionMethods.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;
namespace ExtendedArithmetic
{
public static class ExtensionMethods
{
/// <summary>
/// Fast square root algorithm.
/// It can calculate the square root of numbers with 33,000 digits in < 90 ms,
/// 66,000 digits in < 400 ms,
/// and 100,000 digits in < 900 ms.
/// The previous implementation would have taken tens of minutes or more.
/// Credit for this algorithm goes to: Ryan Scott White.
/// This code was taken from his GitHub, with only minor refactoring changes and
/// changes so it does not depend on .NET 7.0.
/// Check out his GitHub here:
/// https://github.com/SunsetQuest/NewtonPlus-Fast-BigInteger-and-BigFloat-Square-Root
/// </summary>
public static BigInteger SquareRoot(this BigInteger input)
{
if (input < 144838757784765629) // 1.448e17 = ~1<<57
{
uint resultUInt = (uint)Math.Sqrt((ulong)input);
if ((input <= 4503599761588224) && ((ulong)resultUInt * resultUInt > (ulong)input)) // 4.5e15 = ~1<<52
{
resultUInt--;
}
return resultUInt;
}
double inputDouble = (double)input;
if (inputDouble < 8.5e37) // 8.5e37 is V<sup>2</sup>long.max * long.max
{
ulong resultULong = (ulong)Math.Sqrt(inputDouble);
BigInteger result = (resultULong + ((ulong)(input / resultULong))) >> 1;
return (result * result >= input) ? result : result - 1;
}
if (inputDouble < 4.3322e127)
{
BigInteger resultBigInt = (BigInteger)Math.Sqrt(inputDouble);
resultBigInt = (resultBigInt + (input / resultBigInt)) >> 1;
if (inputDouble > 2e63)
{
resultBigInt = (resultBigInt + (input / resultBigInt)) >> 1;
}
return (resultBigInt * resultBigInt >= input) ? resultBigInt : resultBigInt - 1;
}
int bitLength = (int)BigInteger.Log(input, 2.0);
BigInteger testBitLen = BigInteger.Pow(2, bitLength);
BigInteger testBitLenPlus1 = BigInteger.Pow(2, bitLength + 1);
BigInteger diff1 = input - testBitLen;
BigInteger diff2 = input - testBitLenPlus1;
if (diff1 > diff2)
{
bitLength++;
}
int wantedPrecision = (bitLength + 1) / 2;
int bitLengthMod = bitLength + (bitLength & 1) + 1;
// Do the first sqrt on hardware
long tempLong = (long)(input >> (bitLengthMod - 63));
double tempSqrtDouble = Math.Sqrt(tempLong);
ulong valLong = (ulong)BitConverter.DoubleToInt64Bits(tempSqrtDouble) & 0x1fffffffffffffL;
if (valLong == 0)
{
valLong = 1UL << 53;
}
// Classic Newton iterations
BigInteger valBigInt = ((BigInteger)valLong << (53 - 1)) + (input >> bitLengthMod - (3 * 53)) / valLong;
int size = 106;
for (; size < 256; size <<= 1)
{
valBigInt = (valBigInt << (size - 1)) + (input >> bitLengthMod - (3 * size)) / valBigInt;
}
if (inputDouble > 4e254)// 1 << 845
{
int numOfNewtonSteps = (int)Math.Log((uint)(wantedPrecision / size), 2.0) + 2;
// Apply starting size
int wantedSize = (wantedPrecision >> numOfNewtonSteps) + 2;
int needToShiftBy = size - wantedSize;
valBigInt >>= needToShiftBy;
size = wantedSize;
do
{
//Newton plus iterations
int shiftBits = bitLengthMod - (3 * size);
BigInteger valSquared = (valBigInt * valBigInt) << (size - 1);
BigInteger valShifted = (input >> shiftBits) - valSquared;
valBigInt = (valBigInt << size) + (valShifted / valBigInt);
size *= 2;
} while (size < wantedPrecision);
}
// There are a few extra digits here, lets save them
int oversizedBy = size - wantedPrecision;
BigInteger saveDroppedDigitsBigInt = valBigInt & ((BigInteger.One << oversizedBy) - 1);
int undersizedBy = (oversizedBy < 64) ? (oversizedBy >> 2) + 1 : (oversizedBy - 32);
ulong saveDroppedDigitsULong = (ulong)(saveDroppedDigitsBigInt >> undersizedBy);
// Shrink result to wanted precision
valBigInt >>= oversizedBy;
// Detect if should round up
if ((saveDroppedDigitsULong == 0) && (valBigInt * valBigInt > input))
{
valBigInt--;
}
return valBigInt;
}
/// <summary> Returns the Nth root of a BigInteger. The value must be a positive integer and the parameter root must be greater than or equal to 1.</summary>
public static BigInteger NthRoot(this BigInteger source, int root)
{
BigInteger remainder = new BigInteger();
return source.NthRoot(root, out remainder);
}
/// <summary> Returns the Nth root of a BigInteger with remainder. The value must be a positive integer and the parameter root must be greater than or equal to 1.</summary>
public static BigInteger NthRoot(this BigInteger source, int root, out BigInteger remainder)
{
if (root < 1) throw new Exception("Root must be greater than or equal to 1");
if (source.Sign == -1) throw new Exception("Value must be a positive integer");
remainder = 0;
if (source == BigInteger.One) { return BigInteger.One; }
if (source == BigInteger.Zero) { return BigInteger.Zero; }
if (root == 1) { return source; }
BigInteger upperbound = source;
BigInteger lowerbound = BigInteger.Zero;
while (true)
{
BigInteger nval = (upperbound + lowerbound) >> 1;
BigInteger testPow = BigInteger.Pow(nval, root);
if (testPow > source) upperbound = nval;
if (testPow < source) lowerbound = nval;
if (testPow == source)
{
lowerbound = nval;
break;
}
if (lowerbound == upperbound - 1) break;
}
remainder = source - BigInteger.Pow(lowerbound, root);
return lowerbound;
}
public static BigInteger GCD(this IEnumerable<BigInteger> numbers) => numbers.Aggregate(GCD);
public static BigInteger GCD(BigInteger value1, BigInteger value2)
{
var absValue1 = BigInteger.Abs(value1);
var absValue2 = BigInteger.Abs(value2);
while (absValue1 != 0 && absValue2 != 0)
{
if (absValue1 > absValue2)
{
absValue1 %= absValue2;
}
else
{
absValue2 %= absValue1;
}
}
return BigInteger.Max(absValue1, absValue2);
}
public static Int32 GetLength(this BigInteger source)
{
var result = 0;
var copy = BigInteger.Abs(source);
while (copy > 0)
{
copy /= 10;
result++;
}
return result;
}
public static IEnumerable<BigInteger> GetRange(BigInteger min, BigInteger max)
{
while (min < max)
{
yield return min;
min++;
}
}
public static Int32 GetSignifigantDigits(this BigInteger value)
{
if (value.IsZero)
{
return 0;
}
var valueString = value.ToString().TrimEnd('0');
if (String.IsNullOrEmpty(valueString))
{
return 0;
}
if (value < BigInteger.Zero)
{
return valueString.Length - 1;
}
return valueString.Length;
}
public static Boolean IsCoprime(BigInteger value1, BigInteger value2) => GCD(value1, value2) == 1;
public static BigInteger LCM(IEnumerable<BigInteger> numbers) => numbers.Aggregate(LCM);
public static BigInteger LCM(BigInteger num1, BigInteger num2)
{
var absValue1 = BigInteger.Abs(num1);
var absValue2 = BigInteger.Abs(num2);
return absValue1 * absValue2 / GCD(absValue1, absValue2);
}
public static bool Contains(this string source, string value, StringComparison comparisonType)
{
return source?.IndexOf(value, comparisonType) >= 0;
}
}
}