我要实现
BigInteger.ModPow(1/BigInteger, 2,5);
but 1/BigInteger
总是回来0
,这导致结果是0
也。我试着寻找一些BigDecimal
c# 的类,但我什么也没找到。即使没有,有什么方法可以计算这个吗?BigDecimal
?
1/a
对于 |a|>1 来说是 0,因为BigIntegers
使用整数除法,其中忽略除法的小数部分。我不确定您对此期望什么结果。
我假设你想要模乘逆 of a
modulo m
,而不是小数。这个逆存在当且仅当a
and m
是互质的,即gcd(a, m) = 1
.
链接的维基百科页面列出了计算模乘逆的两种标准算法:
-
扩展欧几里得算法,适用于任意模数
它速度很快,但运行时依赖于输入。
我手头没有 C# 代码,但从维基百科移植伪代码应该很简单。
-
Using Euler's theorem:
This requires knowledge of φ(m) i.e. you need to know the prime factors of m. It's a popular choice when m
is a prime and thus φ(m) = m-1 when it simply becomes . If you need constant runtime and you know φ(m), this is the way to go.
在 C# 中这变成了BigInteger.ModPow(a, phiOfM-1, m)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)