【问题标题】:How can modular multiplication and exponentiation be performed in C#?如何在 C# 中执行模乘和求幂?
【发布时间】:2015-05-04 11:13:20
【问题描述】:

如果我知道参数akp,那么如何在 C# 中计算?

s=a*k^-1 mod p

它用于加密目的,我是新手。如果问题不恰当,请不要感到被冒犯。

请注意,k^-1k (mod p) 的模逆,而不是幂运算符。

【问题讨论】:

  • k^-1 表示 k *mod p) 的模逆。 @ArtjomB。
  • akp 有多大?问题是一个 int 就足够了还是需要一个 BigInteger。
  • a,k and p 将与 long 变量一样大。对不起。 @ArtjomB。

标签: c# c#-4.0 modular-arithmetic


【解决方案1】:

由于问题是关于模逆的,我想寻求者看看另一个SO question会有所帮助。

答案的关键是——

Net 4.0+ 使用特殊的模运算函数 ModPow 实现 BigInteger(它产生“X power Y modulo Z”),您不需要第三方库来模拟 ModInverse。如果 m 是素数,您需要做的就是计算:

在 C# 中,根据 MSDN documentation 这被定义为

public static BigInteger ModPow(
    BigInteger value,
    BigInteger exponent,
    BigInteger modulus
)

使用这个我们可以做一些事情,比如计算 k 模 p 的倒数 喜欢

BigInteger bi= ModPow(k, -1, p );
int b= (int) bi;
s= (a* bi )%p;

【讨论】:

【解决方案2】:

public static double DoMath(double a, double k, double p)

    {
        return (a * Math.Pow(k, -1)) % p;
    }

【讨论】:

  • k^-1是模逆,与Math.Pow(k, -1)不同。
猜你喜欢
  • 2020-12-20
  • 2016-05-11
  • 1970-01-01
  • 2014-08-19
  • 2011-04-22
  • 2021-06-13
  • 2021-03-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多