Let d_1, d_2, ..., d_n be the input numbers. Consider all their partial sums:
Since there are exactly partial sums, among all the values of s_i~mod~n there must be either two that are equal or at least one that is zero.
If for some indices a - 1 < b it holds that
then the sum d_a + ... + d_b is divisible by .
Therefore, the sequence of numbers d_a, d_{a + 1}, ..., d_b is a valid solution.
If there exists an such that s_i~mod~n = 0, then the sequence d_1, d_2, ..., d_i forms a valid solution..
Example
Let’s consider the given example. Compute all the partial sums:
There are several valid subsets. For example:
since s_1 = s_3, then d_2 + d_3 = 5 is divisible by .
since s_1 = s_5, then d_2 + d_3 + d_4 + d_5 = 10 is divisible by .
since s_3 = s_5, then d_4 + d_5 = 5 is divisible by .
since s_4 = 0, then d_1 + d_2 + d_3 + d_4 = 10 is divisible by .
Algorithm implementation
We'll store the input numbers in an array . The array will be used to record partial sums: s = d_1 + ... + d_i, then assign r[s] = i.
#define MAX 10100
int d[MAX], r[MAX];The desired set of numbers whose sum is divisible by , will be d_a, d_{a+1}, ..., d_b. Print their count b - a + 1, followed by the numbers themselves — one per line.
void print(int a, int b)
{
printf("%d\n",b - a + 1);
for(int i = a; i <= b; i++)
printf("%d\n",d[i]);
}The main part of the program. Initialize the array with the value and set r[0] = 0 to handle the case when the sum of the first numbers is divisible by .
memset(r,-1,sizeof(r)); r[0] = 0;Read the number of elements .
scanf("%d",&n);Compute the partial sums modulo in the variable .
sum = 0;
for (i = 1; i <= n; i++)
{
scanf("%d", &d[i]);
sum = (sum + d[i]) % n;If a partial sum occurs again, print the desired set of numbers:
if (r[sum] != -1)
{
print(r[sum] + 1, i);
break;
}stores the first index where the partial sum d_1 + ... + d_i produced the remainder when divided by .
else r[sum] = i;
}