How to find modulo of a sum of numbers?

落花浮王杯 提交于 2019-12-23 08:29:12

问题


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.


回答1:


As I can recall. you can:

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

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.

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.

Sample Code

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

Better Approach (not very sure)

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



回答2:


Mod operator is distributive;

( x + y ) % z

... is equivalent to:

( x % z + y % z ) % z


来源:https://stackoverflow.com/questions/26323271/how-to-find-modulo-of-a-sum-of-numbers

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!