From 7ce3167f874b6083627e2b98ccfb881565f1b757 Mon Sep 17 00:00:00 2001 From: Waqar Hassan Khan Date: Fri, 3 Sep 2021 20:42:30 +0600 Subject: [PATCH] chore(CSharp): added algorithm to determine factorial (#437) --- algorithms/CSharp/README.md | 3 +++ algorithms/CSharp/src/Recursion/factorial.cs | 27 +++++++++++++++++++ algorithms/CSharp/test/Recursion/factorial.cs | 18 +++++++++++++ 3 files changed, 48 insertions(+) create mode 100644 algorithms/CSharp/src/Recursion/factorial.cs create mode 100644 algorithms/CSharp/test/Recursion/factorial.cs diff --git a/algorithms/CSharp/README.md b/algorithms/CSharp/README.md index 9273af3b..5430e572 100644 --- a/algorithms/CSharp/README.md +++ b/algorithms/CSharp/README.md @@ -16,3 +16,6 @@ For running the `.cs` file please using [.Net Finddle](https://dotnetfiddle.net/ ## Maths - [Abundant Number](src/Maths/abundant-number.cs) + +## Recusrsion +- [Factorial](src/Recursion/factorial.cs) \ No newline at end of file diff --git a/algorithms/CSharp/src/Recursion/factorial.cs b/algorithms/CSharp/src/Recursion/factorial.cs new file mode 100644 index 00000000..c82b5c09 --- /dev/null +++ b/algorithms/CSharp/src/Recursion/factorial.cs @@ -0,0 +1,27 @@ +using System; + +namespace Algorithms.Recursion +{ + public class Factorial + { + public static int FactorialUsingRecursion(int number) + { + if(number == 0 || number == 1) + { + return 1; + } + + return number * FactorialUsingRecursion(number - 1); + } + + public static void Main() + { + Console.WriteLine($"Factorial of 7 is: {FactorialUsingRecursion(17)}"); + } + } +} + +/* + * n! = n * (n - 1) * (n - 2) * .... * 3 * 2 * 1 + * we have used int here but for larger number, int will not be enough + */ \ No newline at end of file diff --git a/algorithms/CSharp/test/Recursion/factorial.cs b/algorithms/CSharp/test/Recursion/factorial.cs new file mode 100644 index 00000000..8c701731 --- /dev/null +++ b/algorithms/CSharp/test/Recursion/factorial.cs @@ -0,0 +1,18 @@ +using NUnit.Framework; + +namespace Algorithms.Tests.Recursion +{ + [TestFixture] + public class FactorialTest + { + [TestCase(0, 1)] + [TestCase(7, 5040)] + [TestCase(3, 6)] + [TestCase(1, 1)] + public void TestFactorial_ShouldGetExpectedResult(int number, int expected) + { + int result = Algorithms.Recursion.Factorial.FactorialUsingRecursion(number); + Assert.AreEqual(expected, result); + } + } +}