-
-
Save jmcd/8412d289f33c4fdeeb208689276dc30a to your computer and use it in GitHub Desktop.
Long Division
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
public class M | |
{ | |
public static int[] DigitsOf(int value) | |
{ | |
var numbers = new List<int>(); | |
for (; value > 0; value /= 10) | |
{ | |
numbers.Add(value % 10); | |
} | |
return numbers.ToArray(); | |
} | |
public static (int quotient, int remainder) Divide(int dividend, int divisor) | |
{ | |
var digitsOfDividend = DigitsOf(dividend); | |
var quotient = 0; | |
var remainder = 0; | |
for (var power = digitsOfDividend.Length - 1; power >= 0; power--) | |
{ | |
var digit = digitsOfDividend[power]; | |
var number = remainder * 10 + digit; | |
var howManyTimesDoesDivisorGoIntoNumber = number / divisor; | |
quotient += howManyTimesDoesDivisorGoIntoNumber * (int) Math.Pow(10, power); | |
var amount = howManyTimesDoesDivisorGoIntoNumber * divisor; | |
remainder = number - amount; | |
} | |
return (quotient, remainder); | |
} | |
} |
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
public class UnitTest1 | |
{ | |
[Fact] | |
public void CanGetDigits() | |
{ | |
Assert.Equal(new[] {5, 2, 4}, M.DigitsOf(425)); | |
} | |
[Theory] | |
[InlineData(8, 304, 38)] | |
[InlineData(6, 72, 12)] | |
[InlineData(2, 58, 29)] | |
[InlineData(7, 161, 23)] | |
[InlineData(2, 46, 23)] | |
[InlineData(5, 85, 17)] | |
[InlineData(7, 133, 19)] | |
[InlineData(2, 66, 33)] | |
[InlineData(7, 231, 33)] | |
[InlineData(169, 78247, 463)] | |
[InlineData(137, 18084, 132)] | |
[InlineData(61, 21411, 351)] | |
[InlineData(157, 43489, 277)] | |
[InlineData(62, 17050, 275)] | |
[InlineData(106, 20034, 189)] | |
public void WholeNumberDivision(int divisor, int dividend, int expectedQuotient) | |
{ | |
Assert.Equal(expectedQuotient, M.Divide(dividend, divisor).quotient); | |
} | |
[Theory] | |
[InlineData(25, 435, 17, 10)] | |
public void WithRemainderDivision(int divisor, int dividend, int expectedQuotient, int expectedRemainder) | |
{ | |
var (quotient, remainder) = M.Divide(dividend, divisor); | |
Assert.Equal(expectedQuotient, quotient); | |
Assert.Equal(expectedRemainder, remainder); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment