Consider the second test case. What are the remainders when each number is divided by ?
Consider the third test case. What are the remainders when each number is divided by ? Recall how remainders are computed for negative numbers divided by positive numbers.
Let be the largest number such that dividing all numbers a_i by gives the same remainder. What can be said about the difference between any two numbers in the sequence with respect to ?
Represent the numbers a_i as a_i = d \cdot r_i + rest and consider the differences a_{i+1} - a_i. What is the largest possible value of that satisfies these equalities? Recall the definition of the greatest common divisor.
Algorithm analysis
Let a sequence of numbers be given: a_1, a_2, ..., a_k.
If, when dividing each number a_i~(1 \le i \le k) by , the remainder is the same, denote this remainder as . Then each number can be written in the form:
Here r_1, r_2, ..., r_k are integers (the quotients of the divisions).
Now, subtract the consecutive elements of the sequence:
In all these differences, the number is a factor. This means that divides each of the differences: a_2 - a_1, a_3 - a_2, ..., a_k - a_{k-1}.
We are looking for the largest possible that divides all these differences. By definition, the largest number that divides several numbers simultaneously is their greatest common divisor (GCD). Therefore
Since is chosen to be maximal, the numbers r_2 - r_1, r_3 - r_2, ... have no common divisor greater than . Otherwise, this common divisor could be factored out, increasing , which would contradict its maximality. Therefore
Also note that if, for example, from each equation of the form a_i = d \cdot r_i + rest~(2 \le i \le k) we subtract the first one, then the answer can be written as:
Sometimes, computations in this form are more convenient.
Example
For the first test case we have:
Algorithm implementation
The function gcd computes the greatest common divisor of two numbers and .
int gcd(int a, int b)
{
return (!b) ? a : gcd(b, a % b);
}The main part of the program. Read the first number a_1. If it is , this means it is the last line and should not be processed — we exit the loop.
while (scanf("%d", &a), a)
{The variable stores the current result — the greatest common divisor of the differences.
res = 0;Read the next number of the line into the variable . The result is computed using the formula
In the code, the variable stores the value of a_1, while the variable takes the values a_2, a_3, ..., a_k.
while (scanf("%d", &b), b)
res = gcd(res, abs(b - a));Print the answer.
printf("%d\n", res);
}