Little penguin Polo has an *n* × *m* matrix, consisting of integers. Let's index the matrix rows from 1 to *n* from top to bottom and let's index the columns from 1 to *m* from left to right. Let's represent the matrix element on the intersection of row *i* and column *j* as *a*<sub class="lower-index">*ij*</sub>.

In one move the penguin can add or subtract number *d* from some matrix element. Find the minimum number of moves needed to make all matrix elements equal. If the described plan is impossible to carry out, say so.
The first line contains three integers *n*, *m* and *d* (1 ≤ *n*, *m* ≤ 100, 1 ≤ *d* ≤ 10<sup class="upper-index">4</sup>) — the matrix sizes and the *d* parameter. Next *n* lines contain the matrix: the *j*-th integer in the *i*-th row is the matrix element *a*<sub class="lower-index">*ij*</sub> (1 ≤ *a*<sub class="lower-index">*ij*</sub> ≤ 10<sup class="upper-index">4</sup>).
from collections import deque
import math
from random import randint as rand
from functools import lru_cache
import string
alph_l = string.ascii_lowercase
alph_u = string.ascii_uppercase

def binpoisk(a, x):
    l, r = -1, len(a)
    while l +1 < r:
        m = (l + r) // 2
        if a[m] <= x:
            l = m
        else:
            r = m
    return l

def main():
    n, m, d = list(map(int, input().split()))
    table = []
    min_elem = 1000000
    for i in range(n):
        tmp = list(map(int, input().split()))
        table.append(tmp)
    for i in range(n):
        min_elem = min(min_elem, min(table[i]))
    for i in range(n):
        for j in range(m):
            table[i][j] -= min_elem
    max_elem = -1
    for i in range(n):
        max_elem = max(max_elem, max(table[i]))
    pref = []
    for i in range(n):
        for j in range(m):
            if table[i][j] % d != 0:
                return -1
    dp = {}
    for i in range(n):
        table[i].sort()
    for k in range(0, (max_elem)//d+1, 1):
        dp[k] = 0

    for i in range(n):
        for j in range(m):
            table[i][j] //= m

    for i in range(n):
        tmp = []
        tmp.append(table[i][0])
        for j in range(1, m):
            tmp.append(tmp[-1] + table[i][j])
        pref.append(tmp)
    for k in range(0, max_elem//d + 1, 1):
        for i in range(n):
            index = binpoisk(table[i], k)
            if index != -1:
                dp[k] += ((index+1) * k - pref[i][index])
                dp[k] += (pref[i][m-1] - pref[i][index] - (n - index - 1) * k)
            else:
                dp[k] += (pref[i][m-1] - n * k)
    ans = 100000000
    for i in list(dp.keys()):
        ans = min(ans, dp[i])
    return ans


if __name__ == "__main__":
    print(main())