如何求和的模数? [英] How to find modulo of a sum of numbers?

查看:60
本文介绍了如何求和的模数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法来查找数字序列的模,例如: (a1 + a2 + a3 + a4 + ... + an)mod x

I am seeking for a way to find modulo of a sequence of numbers like: (a1 + a2 + a3 + a4 + ... + an) mod x

是否有模函数的任何方式/性质,以便我可以根据序列中各个数字的模数来计算该序列的模数.

Is there any way/property of modulo function so that I can compute mod of this sequence from the individual mods of numbers in sequence.

推荐答案

我记得.您可以:

(a1 mod x + a2 mod x + a3 mod x + ... + an mod x) mod x

这样的方程式将有益于一个目的.如果数字的总和超过用于求和的变量的容量.前任. 32位整数.

Such equation will benefit one purpose. if the sum of the numbers exceeds the capacity of the variable used for summation. ex. 32 bit int.

这样,很可能模块的总和将适合所使用的var中求和.取决于x值和序列长度.

This way it is most probably the sum of modulars will fit in the used var for summation. depending on x value and sequence length.

示例代码

int sum = 0;
for (int i=0;i<n;i++)
   sum += a[i] % x;
int mod = sum % x;

更好的方法(不是很确定)

int sum = 0;
for (int i=0;i<n;i++) {
   sum += a[i] % x;
   sum %= x;
}
int mod = sum;

这篇关于如何求和的模数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆