chore(CSharp): added big mod (#498)
parent
bc34f3bd19
commit
20a485a42c
|
@ -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)
|
||||
|
|
|
@ -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)}");
|
||||
}
|
||||
}
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue