1 Star 0 Fork 63

雁秋 / C-Sharp

forked from 编程语言算法集 / C-Sharp 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
ModularExponentiation.cs 1.26 KB
一键复制 编辑 原始数据 按行查看 历史
Aayush Borkar 提交于 2021-10-23 18:42 . Add Modular Exponentiation (#263)
using System;
namespace Algorithms.Numeric
{
/// <summary>
/// Modular exponentiation is a type of exponentiation performed over a modulus
/// Modular exponentiation c is: c = b^e mod m where b is base, e is exponent, m is modulus
/// (Wiki: https://en.wikipedia.org/wiki/Modular_exponentiation).
/// </summary>
public class ModularExponentiation
{
/// <summary>
/// Performs Modular Exponentiation on b, e, m.
/// </summary>
/// <param name="b">Base.</param>
/// <param name="e">Exponent.</param>
/// <param name="m">Modulus.</param>
/// <returns>Modular Exponential.</returns>
public int ModularPow(int b, int e, int m)
{
// initialize result in variable res
int res = 1;
if (m == 1)
{
// 1 divides every number
return 0;
}
if (m <= 0)
{
// exponential not defined in this case
throw new ArgumentException(string.Format("{0} is not a positive integer", m));
}
for (int i = 0; i < e; i++)
{
res = (res * b) % m;
}
return res;
}
}
}
C#
1
https://gitee.com/xyesterday/C-Sharp.git
git@gitee.com:xyesterday/C-Sharp.git
xyesterday
C-Sharp
C-Sharp
master

搜索帮助