Find a multiple#5621

Let d_1, d_2, ..., d_n be the input numbers. Consider all their partial sums:

s_i = d_1 + ... + d_i

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

s_{a-1}~mod~n = s_b~mod~n,

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:

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:

d_{r[sum] + 1}, d_{r[sum] + 2}, ..., d_i
  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;
}