问题
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