From 49b9a04e20da2f72424ead4932194332445009a4 Mon Sep 17 00:00:00 2001 From: Leefrost Date: Sun, 7 Oct 2018 15:16:46 +0300 Subject: [PATCH] Catalan numbers Due to Contribution.md I added Catalan numbers generator. Test included --- .../CatalanNumbersTests.cs | 48 +++++++++++++++++++ .../CatalanNumbers/CatalanNumberGenerator.cs | 26 ++++++++++ 2 files changed, 74 insertions(+) create mode 100644 Algorithms/Algorithms.Tests/CatalanNumbersTests/CatalanNumbersTests.cs create mode 100644 Algorithms/Algorithms/CatalanNumbers/CatalanNumberGenerator.cs diff --git a/Algorithms/Algorithms.Tests/CatalanNumbersTests/CatalanNumbersTests.cs b/Algorithms/Algorithms.Tests/CatalanNumbersTests/CatalanNumbersTests.cs new file mode 100644 index 0000000..6c2b75f --- /dev/null +++ b/Algorithms/Algorithms.Tests/CatalanNumbersTests/CatalanNumbersTests.cs @@ -0,0 +1,48 @@ +using FluentAssertions; +using Xunit; + +namespace Algorithms.Tests.CatalanNumbersTests +{ + public class CatalanNumbersTests + { + [Fact] + public void GetNumbers_Generate3rdCatalanNumber_Return5() + { + var expected = 5; + + var number = CatalanNumberGenerator.GetNumberOn(3); + + number.Should().Be(expected); + } + + [Fact] + public void GetNumbers_Generate15rdCatalanNumber_Return9694845() + { + var expected = 9694845; + + var number = CatalanNumberGenerator.GetNumberOn(15); + + number.Should().Be(expected); + } + + [Fact] + public void GetNumbers_Generate0rdCatalanNumber_Return1() + { + var expected = 0; + + var number = CatalanNumberGenerator.GetNumberOn(0); + + number.Should().Be(expected); + } + + [Fact] + public void GetNumbers_GenerateNegativePos_Return0() + { + var expected = 0; + + var number = CatalanNumberGenerator.GetNumberOn(-1); + + number.Should().Be(expected); + } + } +} diff --git a/Algorithms/Algorithms/CatalanNumbers/CatalanNumberGenerator.cs b/Algorithms/Algorithms/CatalanNumbers/CatalanNumberGenerator.cs new file mode 100644 index 0000000..afb7ae8 --- /dev/null +++ b/Algorithms/Algorithms/CatalanNumbers/CatalanNumberGenerator.cs @@ -0,0 +1,26 @@ +using System; + +namespace Algorithms +{ + public static class CatalanNumberGenerator + { + private static double Factorial(double n) + { + if (n <= 0.0) + return 1; + + return n * Factorial(n - 1); + } + + public static double GetNumberOn(int n) + { + if (n <= 0) + return 0; + + const double topMultiplier = 2.0; + var result = Factorial(topMultiplier * n) / (Factorial(n + 1) * Factorial(n)); + + return Math.Ceiling(result); + } + } +}