Skip to content

Commit 5239e71

Browse files
Add Ceil numeric algorithm (#490)
1 parent f9f450c commit 5239e71

File tree

3 files changed

+51
-0
lines changed

3 files changed

+51
-0
lines changed

Algorithms.Tests/Numeric/CeilTests.cs

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
using System;
2+
using System.Numerics;
3+
using Algorithms.Numeric;
4+
using NUnit.Framework;
5+
6+
namespace Algorithms.Tests.Numeric;
7+
8+
public static class CeilTests
9+
{
10+
[TestCase(0.0, 0)]
11+
[TestCase(1.1, 2)]
12+
[TestCase(1.9, 2)]
13+
[TestCase(1.0, 1)]
14+
[TestCase(-1.1, -1)]
15+
[TestCase(-1.9, -1)]
16+
[TestCase(-1.0, -1)]
17+
[TestCase(1000000000.1, 1000000001)]
18+
[TestCase(1, 1)]
19+
public static void GetsCeilVal<T>(T inputNum, T expected) where T : INumber<T>
20+
{
21+
// Act
22+
var result = Ceil.CeilVal(inputNum);
23+
24+
// Assert
25+
Assert.That(result, Is.EqualTo(expected));
26+
}
27+
}

Algorithms/Numeric/Ceil.cs

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
using System;
2+
using System.Numerics;
3+
4+
namespace Algorithms.Numeric;
5+
6+
/// <summary>
7+
/// Perform ceiling operation on a number.
8+
/// </summary>
9+
public static class Ceil
10+
{
11+
/// <summary>
12+
/// Returns the smallest integer greater than or equal to the number.
13+
/// </summary>
14+
/// <typeparam name="T">Type of number.</typeparam>
15+
/// <param name="inputNum">Number to find the ceiling of.</param>
16+
/// <returns>Ceiling value of the number.</returns>
17+
public static T CeilVal<T>(T inputNum) where T : INumber<T>
18+
{
19+
T intPart = T.CreateChecked(Convert.ToInt32(inputNum));
20+
21+
return inputNum > intPart ? intPart + T.One : intPart;
22+
}
23+
}

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,7 @@ find more than one implementation for the same objective but using different alg
7171
* [Addition Without Arithmetic](./Algorithms/Numeric/AdditionWithoutArithmetic.cs)
7272
* [Aliquot Sum Calculator](./Algorithms/Numeric/AliquotSumCalculator.cs)
7373
* [Amicable Numbers Checker](./Algorithms/Numeric/AmicableNumbersChecker.cs)
74+
* [Ceil](./Algorithms/Numeric/Ceil.cs)
7475
* [Decomposition](./Algorithms/Numeric/Decomposition)
7576
* [LU Decomposition](./Algorithms/Numeric/Decomposition/LU.cs)
7677
* [Thin Singular Vector Decomposition](./Algorithms/Numeric/Decomposition/ThinSVD.cs)

0 commit comments

Comments
 (0)