chore(CSharp): added big mod (#498)

pull/502/head
Waqar Hassan Khan 2021-09-29 19:31:21 +06:00 committed by GitHub
parent bc34f3bd19
commit 20a485a42c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 52 additions and 0 deletions

View File

@ -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)

View File

@ -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)}");
}
}
}

View File

@ -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);
}
}
}