From 20a485a42c1eaa01db311fcb8cd0fed220f08932 Mon Sep 17 00:00:00 2001 From: Waqar Hassan Khan Date: Wed, 29 Sep 2021 19:31:21 +0600 Subject: [PATCH] chore(CSharp): added big mod (#498) --- algorithms/CSharp/README.md | 3 ++ .../CSharp/src/Number-Theory/big-mod.cs | 28 +++++++++++++++++++ .../CSharp/test/Number-Theory/big-mod.cs | 21 ++++++++++++++ 3 files changed, 52 insertions(+) create mode 100644 algorithms/CSharp/src/Number-Theory/big-mod.cs create mode 100644 algorithms/CSharp/test/Number-Theory/big-mod.cs diff --git a/algorithms/CSharp/README.md b/algorithms/CSharp/README.md index 3839779a..387c6edd 100644 --- a/algorithms/CSharp/README.md +++ b/algorithms/CSharp/README.md @@ -4,6 +4,9 @@ For running the `.cs` file please using [.Net Finddle](https://dotnetfiddle.net/ ## Arrays 1. [Single Number](src/Arrays/single-number.cs) +## Number Theory +1. [Big Mod Algorithm](src/Number-Theory/big-mod.cs) + ## Sorts 1. [Bubble Sort](src/Sorts/bubble-sort.cs) diff --git a/algorithms/CSharp/src/Number-Theory/big-mod.cs b/algorithms/CSharp/src/Number-Theory/big-mod.cs new file mode 100644 index 00000000..3575a5cd --- /dev/null +++ b/algorithms/CSharp/src/Number-Theory/big-mod.cs @@ -0,0 +1,28 @@ +using System; + +namespace Algorithms.NumberTheory +{ + public class BigMod + { + // (a ^ p) % m + public static long Mod(long a, long p, long m) + { + if(p == 0) + { + return 1; + } + if(p % 2 == 1) + { + return ((a % m) * Mod(a, p - 1, m)) % m; + } + + long temp = Mod(a, p / 2, m); + return (temp * temp) % m; + } + + public static void Main() + { + Console.WriteLine($"{Mod(4, 5, 3)}"); + } + } +} diff --git a/algorithms/CSharp/test/Number-Theory/big-mod.cs b/algorithms/CSharp/test/Number-Theory/big-mod.cs new file mode 100644 index 00000000..f3aa7bc8 --- /dev/null +++ b/algorithms/CSharp/test/Number-Theory/big-mod.cs @@ -0,0 +1,21 @@ +using NUnit.Framework; + +namespace Algorithms.Tests.NumberTheory +{ + [TestFixture] + public class BigMod + { + [TestCase(4, 5, 3, 1)] + [TestCase(100001, 122, 13, 12)] + [TestCase(10000, 1000, 118, 36)] + [TestCase(333, 31, 17, 12)] + [TestCase(411, 56, 107, 9)] + [TestCase(100000, 0, 100, 1)] + [TestCase(99999999, 99999, 13, 5)] + public void BigMod_ShouldReturnExpectedResult(long a, long p, long m, long expected) + { + long result = Algorithms.NumberTheory.BigMod.Mod(a, p, m); + Assert.AreEqual(expected, result); + } + } +}