How to find modulo the sum of numbers?

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

Is there a way / property of a modular function so that I can calculate the mod of this sequence from the individual mods of numbers in the sequence.

+5
source share
3 answers

As I remember. You can:

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

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

Thus, most likely, the sum of the modules will correspond to the var used for summation. depending on the value of x and the length of the sequence.

Code example

 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; 
+5
source

The Mod statement is distribution;

 ( x + y ) % z 

... is equivalent to:

 ( x % z + y % z ) % z 
+2
source

$ \ sum_ {i = 1} ^ {N} \ left (i \% m \ right) = \ text {INT} \ left (\ frac {N} {t} \ right) \ CDOT \ left (\ sum_ { = 1} ^ {t-1} I \ right) + \ sum_ {= 1} ^ {N \% t} I = \ text {INT} \ left (\ hydraulic fracture {N} {t} \ right) \ cdot \ frac {(m-1) \ cdot m} {2} + \ frac {N \% m \ cdot (N \% m + 1)} {2} $

-3
source

Source: https://habr.com/ru/post/1204500/


All Articles