Skip to content

Commit 9942c73

Browse files
Copilotdanmoseley
andcommitted
Optimize C# edigits implementation with struct-based approach
Co-authored-by: danmoseley <[email protected]>
1 parent 97932bc commit 9942c73

File tree

4 files changed

+33
-10
lines changed

4 files changed

+33
-10
lines changed

.gitignore

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,4 +39,13 @@ Temporary Items
3939
!.vscode/extensions.json
4040
*.code-workspace
4141

42-
# End of https://www.toptal.com/developers/gitignore/api/vscode,osx
42+
# End of https://www.toptal.com/developers/gitignore/api/vscode,osx
43+
44+
# Build artifacts
45+
*.class
46+
*.exe
47+
*.dll
48+
*.so
49+
*.dylib
50+
*.o
51+
*.pdb

bench/algorithm/edigits/1.cs

Lines changed: 23 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,18 @@
11
using System;
22
using System.Numerics;
33

4+
readonly struct BigPair
5+
{
6+
public readonly BigInteger P;
7+
public readonly BigInteger Q;
8+
9+
public BigPair(BigInteger p, BigInteger q)
10+
{
11+
P = p;
12+
Q = q;
13+
}
14+
}
15+
416
class DigitsOfE
517
{
618
private static readonly double LogOfTau = Math.Log(Math.Tau);
@@ -15,10 +27,10 @@ public static void Main(string[] args)
1527
}
1628

1729
var k = BinarySearch(n);
18-
var (p, q) = SumTerms(0, k - 1);
19-
p += q;
30+
var pair = SumTerms(0, k - 1);
31+
var p = BigInteger.Add(pair.P, pair.Q);
2032
var a = BigInteger.Pow(new BigInteger(10), n - 1);
21-
var answer = p * a / q;
33+
var answer = BigInteger.Divide(BigInteger.Multiply(p, a), pair.Q);
2234
var answerStr = answer.ToString();
2335
Span<char> sb = stackalloc char[10];
2436
for (var i = 0; i < n; i += 10)
@@ -44,16 +56,18 @@ public static void Main(string[] args)
4456
}
4557
}
4658

47-
static (BigInteger, BigInteger) SumTerms(int a, int b)
59+
static BigPair SumTerms(int a, int b)
4860
{
4961
if (b == a + 1)
5062
{
51-
return (BigInteger.One, new BigInteger(b));
63+
return new BigPair(BigInteger.One, new BigInteger(b));
5264
}
5365
var mid = (a + b) / 2;
54-
var (pLeft, qLeft) = SumTerms(a, mid);
55-
var (pRight, qRight) = SumTerms(mid, b);
56-
return (pLeft * qRight + pRight, qLeft * qRight);
66+
var pairLeft = SumTerms(a, mid);
67+
var pairRight = SumTerms(mid, b);
68+
return new BigPair(
69+
BigInteger.Add(BigInteger.Multiply(pairLeft.P, pairRight.Q), pairRight.P),
70+
BigInteger.Multiply(pairLeft.Q, pairRight.Q));
5771
}
5872

5973
static int BinarySearch(int n)
@@ -82,7 +96,7 @@ static int BinarySearch(int n)
8296

8397
static bool TestK(int n, int k)
8498
{
85-
if (k <= 0)
99+
if (k < 0)
86100
{
87101
return false;
88102
}
-323 Bytes
Binary file not shown.

bench/algorithm/edigits/app.class

-2.38 KB
Binary file not shown.

0 commit comments

Comments
 (0)