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>).
# ﷽
import sys
import heapq
input = sys.stdin.readline
from math import log2,ceil,floor,gcd,sqrt,log,perm,comb,factorial
from collections import Counter,deque
from random import getrandbits

RANDOM = getrandbits(32)
 
class Wrapper(int):
    def __init__(self, x):
        int.__init__(x)
    def __hash__(self):
        return super(Wrapper, self).__hash__() ^ RANDOM 



# sys.setrecursionlimit(10**4)

def dijkstra(graph, start):
    distances = {node: float('inf') for node in graph}  # Initialize distances to infinity
    distances[start] = 0  # Distance from start to start is 0
    heap = [(0, start,[start])]  # Priority queue to store nodes and their distances
    paths = [-1 for i in range(n+1)]
    while heap:
        current_distance, current_node , path = heapq.heappop(heap)  # Get node with smallest distance
        
        if current_distance > distances[current_node]:
            continue  # Skip if distance is already greater than the known distance

        for neighbor, weight in graph[current_node]:
            distance = current_distance + weight  # Calculate tentative distance

            if distance < distances[neighbor]:
                lst = path 
                lst.append(neighbor)
                paths[neighbor] = current_node
                distances[neighbor] = distance  # Update distance if shorter
                heapq.heappush(heap, (distance, neighbor, lst))  # Add neighbor to the heap

    return paths
divisors = {}
def Divisors(n) :
    for num in range(1,n+1):
        lst = set()
        i = 1
        while i <= sqrt(num):
            
            if (num % i == 0) :
                # If divisors are equal, print only one
                if ( num / i == i) :
                    lst.add(i)
                else :
                    # Otherwise print both
                    lst.update([i,num//i])
                
            i = i + 1
        divisors[num] = list(lst)

Divisors(2000)

def mergeSort(arr, n):
    # A temp_arr is created to store
    # sorted array in merge function
    temp_arr = [0]*n
    return _mergeSort(arr, temp_arr, 0, n-1)
 
# This Function will use MergeSort to count inversions
 
 
def _mergeSort(arr, temp_arr, left, right):
 
    # A variable inv_count is used to store
    # inversion counts in each recursive call
 
    inv_count = 0
 
    # We will make a recursive call if and only if
    # we have more than one elements
 
    if left < right:
 
        # mid is calculated to divide the array into two subarrays
        # Floor division is must in case of python
 
        mid = (left + right)//2
 
        # It will calculate inversion
        # counts in the left subarray
 
        inv_count += _mergeSort(arr, temp_arr,
                                left, mid)
 
        # It will calculate inversion
        # counts in right subarray
 
        inv_count += _mergeSort(arr, temp_arr,
                                mid + 1, right)
 
        # It will merge two subarrays in
        # a sorted subarray
 
        inv_count += merge(arr, temp_arr, left, mid, right)
    return inv_count
 
# This function will merge two subarrays
# in a single sorted subarray
 
 
def merge(arr, temp_arr, left, mid, right):
    i = left     # Starting index of left subarray
    j = mid + 1  # Starting index of right subarray
    k = left     # Starting index of to be sorted subarray
    inv_count = 0
 
    # Conditions are checked to make sure that
    # i and j don't exceed their
    # subarray limits.
 
    while i <= mid and j <= right:
 
        # There will be no inversion if arr[i] <= arr[j]
 
        if arr[i] <= arr[j]:
            temp_arr[k] = arr[i]
            k += 1
            i += 1
        else:
            # Inversion will occur.
            temp_arr[k] = arr[j]
            inv_count += (mid-i + 1)
            k += 1
            j += 1
 
    # Copy the remaining elements of left
    # subarray into temporary array
    while i <= mid:
        temp_arr[k] = arr[i]
        k += 1
        i += 1
 
    # Copy the remaining elements of right
    # subarray into temporary array
    while j <= right:
        temp_arr[k] = arr[j]
        k += 1
        j += 1
 
    # Copy the sorted subarray into Original array
    for loop_var in range(left, right + 1):
        arr[loop_var] = temp_arr[loop_var]
 
    return inv_count

def add_edge(node1,node2):
    if node1 not in graph:
        graph[node1] = []
    if node2 not in graph:
        graph[node2] = []
    graph[node1].append(node2)
    graph[node2].append(node1)
    
def bfs(node):
    q = deque()
    q.append(node)
    vis.add(node)
    while q:
        a = q.popleft()
        for i in graph[a]:
            if i in vis:
                continue
            vis.add(i)
            q.append(i)

# def bfs(n):
#     q = deque()
#     q.append([n,0])
#     vis = {n:0}
#     ans = []
#     while q:
#         x , dis = q.popleft()
#         ans.append(x)
#         graph[x].sort()
#         for k,child in graph[x] :
#             if child not in vis :
#                 q.append([child,dis + 1])
#                 vis[child] = dis + 1
#     return ans
    
def mergeDictionary(dict_1, dict_2):
   dict_3 = {**dict_1, **dict_2}
   for key, value in dict_3.items():
       if key in dict_1 and key in dict_2:
               dict_3[key] = value + dict_1[key]
   return dict_3
   
def rindex(lst, value):
    lst.reverse()
    i = lst.index(value)
    lst.reverse()
    return len(lst) - i - 1
    
def mex(arr, N):

    # Sort the array
    arr1 = arr.copy()
    arr1.sort()
    
    mex = 0
    for idx in range(N):
        if arr1[idx] == mex:

            # Increment mex
            mex += 1

    # return mex as answer
    return mex
    
def fill_prefix_sum(arr, length_arr, prefix_sum):
    prefix_sum[0] = arr[0] 

    for i in range(1, length_arr): # 1, 2, 3, 4
        prefix_sum[i] =  prefix_sum[i-1]+ arr[i]
        
def fill_suffix_sum(arr, length_arr, suffix_sum):
    suffix_sum[length_arr-1] = arr[length_arr-1] 

    for i in reversed(range(length_arr-1)): # 3, 2, 1, 0
        suffix_sum[i] = suffix_sum[i+1] + arr[i]

    
letters = [
    'a','b','c','d','e','f',
    'g','h','i','j','k','l',
    'm','n','o','p','q','r',
    's','t','u','v','w','x',
    'y','z']

mod = 10**9 + 7
stop_reading_my_code = 1 #int(input().strip())



def f(n) :
    q = deque()
    memo = {}
    q.append([n,0])
    while q:
        a,dis = q.popleft()
        if a%32768 == 0:
            return dis
        if dis == 15 :
            continue
        if (a + 1)%32768 not in memo:
            q.append([(a+1)%32768,dis+1])
            memo[(a + 1)%32768] = dis+1
        if (a*2)%32768 not in memo:
            q.append([(a*2)%32768,dis+1])
            memo[(a*2)%32768] = dis+1
    
from bisect import bisect_left  

for _ in range(stop_reading_my_code):
    graph = {}
    # n = int(input().strip())
    n,m, k  = list(map(Wrapper,input().strip().split()))
    arr = [] 
    for i in range(n) :
        new = list(map(Wrapper,input().strip().split()))
        arr.extend(new)
    arr.sort()
    median1 = arr[(n*m) //2 -1]
    median2 = arr[(n*m) //2 ]
    ans1 = 0 
    ans2 = 0
    for i in arr :
        if abs(median1-i)%k == 0 :
            ans1 += abs(median1-i)//k
        else:
            ans1 = -1 
            break
    for i in arr :
        if abs(median2-i)%k == 0 :
            ans2 += abs(median2-i)//k
        else:
            ans2 = -1 
            break
    if ans1 == -1 :
        if ans2 == -1 :
            print(-1)
        else:
            print(ans2)
    else:
        print(min(ans1,ans2)) if ans2 != -1 else print(ans1)

