如何取存储在数组中的大值的模数?

How to take modulus of a large value stored in array?

假设我有一个包含数字的整数数组,我想对存储在其中的值取模,即

 int a[36]={1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9} 

并将其转换为类似 987654321987654321987654321987654321 的数字。

在 C 语言中 long long int 只允许 10^18。我想取 10^9+7 的模数。我怎样才能做到这一点?

节目:

int main()
{
int a[36]={1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9};
long long int temp=0;
int i;
for(i=0;i<36;i++)
{
     temp=temp+a[i]*pow(10,i);
}
temp=temp%1000000007;
printf("%lld",temp);
return 0;
}

由于 36 位十进制数字对于典型 long long 来说太多了,您需要在转换期间执行模数运算:

int a[36]={1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9};
long long int temp=0;
for(int i=35 ; i >= 0 ; i--) {
    temp = 10*temp + a[i];
    temp %= 1000000007;
}
printf("%lld",temp);

我对你的代码做了两处修改:

  • 修复了将数字数组转换为数字的方式 - 您的代码使用了 pow,并将较高索引处的数字视为较高阶数字。一旦你超过了可以表示为 double.
  • 的十的最高次方,这就会产生精度问题
  • %= 移动到循环中 - 您的代码不会让数字溢出,方法是将值保持在 0 到 1000000006(含)范围内。

运行 此代码 produces the same value that you would obtain with a library that supports arbitrary precision of integers (I used Java BigInteger here).