Skip to content

Commit 8b13d21

Browse files
committed
Ceiling Divide BigInteger extension
1 parent 5dd874c commit 8b13d21

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed

src/Neo.Extensions/BigIntegerExtensions.cs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,22 @@ namespace Neo.Extensions
1818
{
1919
public static class BigIntegerExtensions
2020
{
21+
/// <summary>
22+
/// Performs integer division with ceiling (rounding up).
23+
/// Example: 10 / 3 = 4 instead of 3.
24+
/// </summary>
25+
/// <param name="a">The dividend.</param>
26+
/// <param name="b">The divisor (must be greater than zero).</param>
27+
/// <returns>The result of division rounded up.</returns>
28+
/// <exception cref="ArgumentException">Thrown when divisor is zero or negative.</exception>
29+
public static BigInteger CeilingDivide(this BigInteger a, BigInteger b)
30+
{
31+
if (b <= 0)
32+
throw new ArgumentException("Divider must be greater than zero.", nameof(b));
33+
34+
return (a + b - 1) / b;
35+
}
36+
2137
internal static int TrailingZeroCount(byte[] b)
2238
{
2339
var w = 0;

tests/Neo.Extensions.Tests/UT_BigIntegerExtensions.cs

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,49 @@ namespace Neo.Extensions.Tests
2020
[TestClass]
2121
public class UT_BigIntegerExtensions
2222
{
23+
[TestMethod]
24+
public void CeilingDivide_DividesExactly()
25+
{
26+
var result = BigIntegerExtensions.CeilingDivide(9, 3);
27+
Assert.AreEqual(3, result);
28+
}
29+
30+
[TestMethod]
31+
public void CeilingDivide_RoundsUp()
32+
{
33+
var result = BigIntegerExtensions.CeilingDivide(10, 3);
34+
Assert.AreEqual(4, result);
35+
}
36+
37+
[TestMethod]
38+
public void CeilingDivide_LargeNumbers()
39+
{
40+
var a = BigInteger.Parse("1000000000000000000000000000000000");
41+
var b = new BigInteger(7);
42+
var result = BigIntegerExtensions.CeilingDivide(a, b);
43+
44+
Assert.AreEqual((a + b - 1) / b, result);
45+
}
46+
47+
[TestMethod]
48+
public void CeilingDivide_DivisorOne()
49+
{
50+
var result = BigIntegerExtensions.CeilingDivide(12345, 1);
51+
Assert.AreEqual(12345, result);
52+
}
53+
54+
[TestMethod]
55+
public void CeilingDivide_ThrowsOnZeroDivisor()
56+
{
57+
Assert.Throws<ArgumentException>(() => BigIntegerExtensions.CeilingDivide(10, 0));
58+
}
59+
60+
[TestMethod]
61+
public void CeilingDivide_ThrowsOnNegativeDivisor()
62+
{
63+
Assert.Throws<ArgumentException>(() => BigIntegerExtensions.CeilingDivide(10, -5));
64+
}
65+
2366
[TestMethod]
2467
public void TestGetLowestSetBit()
2568
{

0 commit comments

Comments
 (0)