我经历了下面提到的教程,我尝试计算C和Java中数字的模数反转,但在这两种情况下,我得到输出为0,请指导我纠正我的代码。< / p>
https://www.hackerearth.com/practice/math/number-theory/multiplicative-inverse/tutorial/
import java.lang.Math;
import java.util.*;
import java.math.BigInteger;
import java.math.BigDecimal;
class TestClass {
public static void main(String args[] ) throws Exception {
Scanner sc=new Scanner(System.in);
int a=sc.nextInt();
BigInteger bi=BigInteger.valueOf(a);
BigInteger k = new BigDecimal(Math.pow(10,9)).toBigInteger();
BigInteger b=k.add(BigInteger.valueOf(7));
BigInteger c=b.subtract(BigInteger.valueOf(2));
BigInteger m=bi.modPow(c,BigInteger.valueOf(1));
BigInteger d=m.mod(b);
System.out.println(d);
}
}
在C中,
#include <stdio.h>
#include<inttypes.h>
#include<math.h>
int main()
{
uintmax_t a;
scanf(" %ju",&a);
uintmax_t b=pow(10,9);
uintmax_t m=b+7;
uintmax_t c=((uintmax_t)pow(a,m-2))%(m);
printf("%ju",c);
return 0;
}
我无法理解溢出背后的原因,请澄清一下。
答案 0 :(得分:1)
您的java代码不起作用的原因是
BigInteger m=bi.modPow(c,BigInteger.valueOf(1));
计算bi^c mod 1
,其中bi
和c
为0。
您要计算的是bi^c mod b
,其编码为
BigInteger m = bi.modPow(c, b);
由于C没有powmod
功能,您需要自己编程。
以下函数计算x^e mod m
:
uintmax_t powmod(uintmax_t x, uintmax_t e, uintmax_t m) {
uintmax_t result = 1;
while (e > 0) {
if (e&1) {
result = result * x % m;
}
x = x * x % m;
e >>= 1;
}
return result;
}