Created
June 15, 2022 15:12
-
-
Save TheBuzzSaw/f156d519f74159895f776e951353b6a4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Text; | |
namespace Kelly.Digits; | |
static class Program | |
{ | |
static string Divide(long dividend, long divisor, int maxCycles = 128) | |
{ | |
var builder = new StringBuilder(); | |
var quotient = dividend / divisor; | |
builder.Append(quotient); | |
if (0 < maxCycles) | |
{ | |
var indexByRemainder = new Dictionary<long, int>(); | |
var remainder = dividend % divisor; | |
if (remainder != 0) | |
{ | |
var remainingCycles = maxCycles; | |
var nextDividend = remainder * 10; | |
var nextQuotient = nextDividend / divisor; | |
var nextRemainder = nextDividend % divisor; | |
var index = builder.Length + 1; | |
builder.Append('.').Append(nextQuotient); | |
indexByRemainder.Add(nextDividend, index); | |
while (nextRemainder != 0 && 0 < --remainingCycles) | |
{ | |
nextDividend = nextRemainder * 10; | |
nextQuotient = nextDividend / divisor; | |
nextRemainder = nextDividend % divisor; | |
if (indexByRemainder.TryAdd(nextDividend, ++index)) | |
{ | |
builder.Append(nextQuotient); | |
} | |
else | |
{ | |
var firstIndex = indexByRemainder[nextDividend]; | |
builder.Insert(firstIndex, '[').Append(']'); | |
break; | |
} | |
} | |
} | |
} | |
builder.Append("..."); | |
return builder.ToString(); | |
} | |
static void Main(string[] args) | |
{ | |
Console.WriteLine(Divide(30, 5)); | |
Console.WriteLine(); | |
Console.WriteLine(Divide(1, 70)); | |
Console.WriteLine(); | |
Console.WriteLine(Divide(24, 2300)); | |
Console.WriteLine(); | |
Console.WriteLine(Divide(11, 99900)); | |
Console.WriteLine(Divide(1, 30)); | |
Console.WriteLine(Divide(1, 9)); | |
Console.WriteLine(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment