Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add numeric algorithm - ModularExponentiation #263

Merged
merged 8 commits into from
Oct 23, 2021
Merged
Prev Previous commit
Next Next commit
Update ModularExponentiation
  • Loading branch information
aayushborkar14 committed Oct 22, 2021
commit 554d67694673f1ce98b680bc632b4bb79cb088a6
12 changes: 11 additions & 1 deletion Algorithms.Tests/Numeric/ModularExponentiationTest.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Algorithms.Numeric;
using System;
using NUnit.Framework;
using FluentAssertions;

Expand All @@ -14,12 +15,21 @@ public class ModularExponentiationTest
[TestCase(7, 2, 11, 5)]
[TestCase(4, 13, 497, 445)]
[TestCase(13, 3, 1, 0)]
[TestCase(17, 7, -3, -1)]
public void ModularExponentiationCorrect(int b, int e, int m, int expectedRes)
{
var modularExponentiation = new ModularExponentiation();
var actualRes = modularExponentiation.ModularPow(b, e, m);
actualRes.Should().Be(expectedRes);
}

[TestCase(17, 7, -3)]
[TestCase(11, 3, -5)]
public void ModularExponentiationNegativeMod(int b, int e, int m)
{
var modularExponentiation = new ModularExponentiation();
Action res = () => modularExponentiation.ModularPow(b, e, m);
res.Should().Throw<ArgumentException>()
.WithMessage("modulus cannot be negative");
}
}
}
6 changes: 3 additions & 3 deletions Algorithms/Numeric/ModularExponentiation.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System.Text;
using System;

namespace Algorithms.Numeric
{
Expand All @@ -22,14 +22,14 @@ public int ModularPow(int b, int e, int m)
int res = 1;
if (m == 1)
{
// 1 divides every number
// single element in ring of integers modulo 1
return 0;
}

if (m < 0)
{
// exponential not defined in this case
return -1;
throw new ArgumentException("modulus cannot be negative");
}

for (int i = 0; i < e; i++)
Expand Down