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_{ij}.

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.


-----Input-----

The first line contains three integers n, m and d (1 ≤ n, m ≤ 100, 1 ≤ d ≤ 10^4) — 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_{ij} (1 ≤ a_{ij} ≤ 10^4).


-----Output-----

In a single line print a single integer — the minimum number of moves the penguin needs to make all matrix elements equal. If that is impossible, print "-1" (without the quotes).


-----Examples-----
Input
2 2 2
2 4
6 8

Output
4

Input
1 2 7
6 7

Output
-1

Source: codeforces | Difficulty: MEDIUM
Tags: Dynamic programming

Sorting

Implementation

Complete search


Solutions:
(n, m, d) = map(int, input().split())
c = []
for i in range(n):
	l = list(map(int, input().split()))
	c += l
v = c[0] % d
flag = False
for i in c:
	if i % d != v:
		flag = True
		break
if flag:
	print(-1)
else:
	c.sort()
	median = c[n * m // 2]
	count = 0
	for i in range(n * m):
		if i < n * m // 2:
			count += abs((median - c[i]) // d)
		else:
			count += abs(c[i] - median) // d
	print(count)


import sys
(n, m, d) = map(int, input().split())
L = []
for i in range(n):
	L.extend(list(map(int, input().split())))
L.sort()
(moves, middle) = (0, n * m // 2)
for i in range(n * m):
	if abs(L[middle] - L[i]) % d != 0:
		print('-1')
		sys.exit(0)
		break
	else:
		moves += abs(L[middle] - L[i]) // d
print(moves)
sys.exit(0)


import math
import sys
from bisect import bisect_right, bisect_left, insort_right
from collections import Counter, defaultdict
from heapq import heappop, heappush
from itertools import accumulate
from sys import stdout
R = lambda : map(int, input().split())
(n, m, d) = R()
arr = []
for i in range(n):
	arr += list(R())
arr.sort()
if any([(x - arr[0]) % d for x in arr]):
	print('-1')
	exit(0)
arr = [(x - arr[0]) // d for x in arr]
acc = list(accumulate(arr))
res = math.inf
for x in range(arr[-1] + 1):
	i = bisect_right(arr, x) - 1
	res = min(res, (i + 1) * x - acc[i] + acc[-1] - acc[i] - (n * m - i - 1) * x)
print(res)


(n, m, d) = map(int, input().split())
a = []
for i in range(n):
	a += list(map(int, input().split()))
a.sort()
mid = a[len(a) // 2]
ans = 0
for i in a:
	r = abs(mid - i)
	if r % d != 0:
		print(-1)
		exit()
	else:
		ans += r // d
print(ans)


from math import *
from sys import stdin, stdout
input = stdin.buffer.readline
ip = [int(x) for x in input().split()]
n = ip[0]
m = ip[1]
d = ip[2]
a = []
for i in range(n):
	temp = [int(x) for x in input().split()]
	for j in range(m):
		a.append(temp[j])
a.sort()
ans = 1000000000000000000
tot = 0
pre = [0]
n = len(a)
for i in range(n):
	tot += a[i]
	pre.append(tot)
cost = 1000000000000000000
for i in range(n):
	total = tot + 2 * (i * a[i] - pre[i])
	val = abs(n * a[i] - total)
	if val % d == 0:
		cost = val // d
	if cost < ans:
		ans = cost
		ind = i
check = a[0] % d
for i in range(n):
	if a[i] % d != check:
		ans = 1000000000000000000
		break
if ans < 1000000000000000000:
	print(ans)
else:
	print(-1)


def arr_inp():
	return [int(x) for x in stdin.readline().split()]
from sys import stdin
(n, m, d) = arr_inp()
(matrix, diff, s) = ([], [], 0)
for i in range(n):
	row = arr_inp()
	matrix.extend(row)
matrix.sort()
for i in range(1, m * n):
	tem = matrix[i] - matrix[i - 1]
	if tem % d:
		exit(print(-1))
ans = float('inf')
for i in range(n * m):
	tem = 0
	for j in range(0, i):
		tem += matrix[i] - matrix[j]
	for j in range(i + 1, n * m):
		tem += matrix[j] - matrix[i]
	ans = min(ans, tem // d)
print(ans)


import sys
from functools import reduce
from collections import Counter
import time
import datetime
from math import sqrt, gcd

def ip():
	return int(sys.stdin.readline())

def sip():
	return sys.stdin.readline()

def mip():
	return map(int, sys.stdin.readline().split())

def mips():
	return map(str, sys.stdin.readline().split())

def lip():
	return list(map(int, sys.stdin.readline().split()))

def matip(n, m):
	lst = []
	for i in range(n):
		arr = lip()
		lst.append(arr)
	return lst

def factors(n):
	return list(set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0))))

def minJumps(arr, n):
	jumps = [0 for i in range(n)]
	if n == 0 or arr[0] == 0:
		return float('inf')
	jumps[0] = 0
	for i in range(1, n):
		jumps[i] = float('inf')
		for j in range(i):
			if i <= j + arr[j] and jumps[j] != float('inf'):
				jumps[i] = min(jumps[i], jumps[j] + 1)
				break
	return jumps[n - 1]

def dic(arr):
	return Counter(arr)

def find_prime(n):
	if n < 2:
		return False
	for i in range(2, int(n ** 0.5) + 1, 2):
		if n % i == 0:
			return False
	return True
(n, m, d) = mip()
lst = []
for i in range(n):
	lst.extend(lip())
lst.sort()
mod = lst[0] % d
flag = 0
count = 0
median = lst[n * m // 2]
for item in lst:
	if item % d != mod:
		flag = 1
		break
	else:
		count += abs(median - item)
if flag == 0:
	print(count // d)
else:
	print(-1)


(n, m, d) = map(int, input().split())
matrix = []
for _ in range(n):
	matrix.append(list(map(int, input().split())))
arr = []
modd = matrix[0][0] % d
for i in range(n):
	for j in range(m):
		if modd != matrix[i][j] % d:
			print(-1)
			exit()
		else:
			arr.append(matrix[i][j])
arr.sort()
median = arr[int(len(arr) // 2)]
count = 0
for i in range(n):
	for j in range(m):
		diff = abs(matrix[i][j] - median)
		count += diff // d
print(count)


import sys, math
from collections import deque, defaultdict
import operator as op
from functools import reduce
from itertools import permutations
I = sys.stdin.readline

def ii():
	return int(I().strip())

def li():
	return list(map(int, I().strip().split()))

def mi():
	return map(int, I().strip().split())

def ncr(n, r, p):
	num = den = 1
	for i in range(r):
		num = num * (n - i) % p
		den = den * (i + 1) % p
	return num * pow(den, p - 2, p) % p

def gcd(x, y):
	while y:
		(x, y) = (y, x % y)
	return x

def valid(row, col, rows, cols, rcross, lcross):
	return rows[row] == 0 and cols[col] == 0 and (rcross[col + row] == 0) and (lcross[col - row] == 0)

def div(n):
	if n == 1:
		return 1
	cnt = 2
	for i in range(2, int(n ** 0.5) + 1):
		if n % i == 0:
			if i != n // i:
				cnt += 2
			else:
				cnt += 1
	return cnt

def isPrime(n):
	if n <= 1:
		return False
	elif n <= 2:
		return True
	else:
		flag = True
		for i in range(2, int(n ** 0.5) + 1):
			if n % i == 0:
				flag = False
				break
		return flag

def s(b):
	ans = []
	while b > 0:
		tmp = b % 10
		ans.append(tmp)
		b = b // 10
	return ans

def main():
	(n, m, d) = mi()
	arr = []
	for i in range(n):
		tmp = li()
		for i in tmp:
			arr.append(i)
	arr.sort()
	flag = 1
	for i in range(1, n * m):
		if (arr[i] - arr[i - 1]) % d != 0:
			flag = 0
			break
	if flag:
		ind = n * m // 2
		cnt = 0
		for i in arr:
			cnt += abs(i - arr[ind]) // d
		print(cnt)
	else:
		print(-1)
main()


from sys import stdin
(n, m, d) = map(int, stdin.readline().split())
temp = []
for i in range(n):
	temp.extend(list(map(int, stdin.readline().split())))
res = 1000000000.0
for i in temp:
	t = 0
	f = 1
	for j in temp:
		if j < i:
			if (i - j) / d != (i - j) // d:
				f = 0
				break
			else:
				t += (i - j) // d
		elif (j - i) / d != (j - i) // d:
			f = 0
			break
		else:
			t += (j - i) // d
	if f:
		res = min(res, t)
if res == 1000000000.0:
	print(-1)
else:
	print(res)


import math
from collections import Counter
L = lambda : list(map(int, input().split()))
M = lambda : map(int, input().split())
I = lambda : int(input())
IN = lambda : input()
mod = 10 ** 9 + 7

def s(a):
	print(' '.join(list(map(str, a))))
(m, n, d) = M()
a = []
for i in range(m):
	a += L()
a.sort()
moves = 0
mid = a[m * n // 2]
for i in a:
	x = abs(i - mid)
	if x % d == 0:
		moves += x // d
	else:
		print(-1)
		exit()
print(moves)


import sys
inf = float('inf')

def get_array():
	return list(map(int, sys.stdin.readline().strip().split()))

def get_ints():
	return map(int, sys.stdin.readline().strip().split())

def input():
	return sys.stdin.readline().strip()
(n, m, d) = get_ints()
mat = []
for i in range(n):
	mat.append(get_array())
x = mat[0][0] % d
Arr = []
for i in range(n):
	for j in range(m):
		if mat[i][j] % d != x:
			print(-1)
			exit()
		Arr.append(mat[i][j])
Arr.sort()
length = len(Arr)
if length & 1:
	x = Arr[length // 2]
	count = 0
	for i in Arr:
		count += abs(i - x) // d
	print(count)
else:
	x = Arr[length // 2]
	y = Arr[length // 2 + 1]
	ct1 = 0
	ct2 = 0
	for i in Arr:
		ct1 += abs(i - x) // d
		ct2 += abs(i - y) // d
	print(min(ct1, ct2))


import os
import sys
from io import BytesIO, IOBase

def check(l, d):
	temp = l[0] % d
	for item in l:
		if item % d != temp:
			return 0
	return 1

def main():
	(n, m, d) = map(int, input().split())
	l = []
	for _ in range(n):
		l += list(map(int, input().split()))
	if check(l, d):
		l.sort()
		mid = n * m // 2
		temp = l[mid]
		ans = 0
		for item in l:
			ans += abs(temp - item) // d
		print(ans)
	else:
		print(-1)

def nouse0():
	a = 420
	b = 420
	print(f'i am nitish{(a + b) // 2}')

def nouse1():
	a = 420
	b = 420
	print(f'i am nitish{(a + b) // 2}')

def nouse2():
	a = 420
	b = 420
	print(f'i am nitish{(a + b) // 2}')
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def nouse3():
	a = 420
	b = 420
	print(f'i am nitish{(a + b) // 2}')

def nouse4():
	a = 420
	b = 420
	print(f'i am nitish{(a + b) // 2}')

def nouse5():
	a = 420
	b = 420
	print(f'i am nitish{(a + b) // 2}')
main()


import sys
(n, m, d) = map(int, sys.stdin.readline().strip().split())
p = []
for i in range(n):
	l = list(map(int, sys.stdin.readline().strip().split()))
	p.append(l)
f = 0
r = p[0][0] % d
for i in range(n):
	for j in range(m):
		if r == p[i][j] % d:
			pass
		else:
			f = 1
			break
	if f == 1:
		break
if f == 1:
	print(-1)
else:
	final = []
	for i in range(n):
		for j in range(m):
			final.append(p[i][j])
	final.sort()
	if len(final) % 2 != 0:
		md = len(final) // 2
		k = final[md]
		ans = 0
		for i in range(n):
			for j in range(m):
				if k == p[i][j]:
					pass
				else:
					ans += abs(k - p[i][j]) // d
		print(ans)
	else:
		md1 = len(final) // 2
		md2 = len(final) // 2 - 1
		ans1 = 0
		k = final[md1]
		for i in range(n):
			for j in range(m):
				if k == p[i][j]:
					pass
				else:
					ans1 += abs(k - p[i][j]) // d
		ans2 = 0
		k = final[md2]
		for i in range(n):
			for j in range(m):
				if k == p[i][j]:
					pass
				else:
					ans2 += abs(k - p[i][j]) // d
		print(min(ans1, ans2))


def ii():
	return int(input())

def si():
	return input()

def mi():
	return map(int, input().split())

def msi():
	return map(str, input().split())

def li():
	return list(mi())
(nr, m, d) = mi()
a = []
for _ in range(nr):
	a += li()
flag = 0
n = nr * m
a.sort()
for i in range(1, n):
	if (a[i] - a[i - 1]) % d != 0:
		flag = 1
		break
if flag == 0:
	(pre, suf) = ([0] * n, [0] * n)
	pre[0] = a[0]
	suf[n - 1] = a[n - 1]
	for i in range(1, n):
		pre[i] = pre[i - 1] + a[i]
	for i in range(n - 2, -1, -1):
		suf[i] = suf[i + 1] + a[i]
	ans = 1000000000
	for i in range(n):
		ans = min(ans, (a[i] * (i + 1) - pre[i]) // d + (suf[i] - a[i] * (n - i)) // d)
	print(ans)
else:
	print(-1)


(n, m, d) = map(int, input().split())
a = []
for i in range(n):
	a += list(map(int, input().split()))
a.sort()
c = a[len(a) // 2]
count = 0
for i in a:
	b = abs(c - i)
	if b % d != 0:
		print(-1)
		exit()
	else:
		f = b // d
		count += f
print(count)


class CodeforcesTask289BSolution:

	def __init__(self):
		self.result = ''
		self.n_m_d = []
		self.matrix = []

	def read_input(self):
		self.n_m_d = [int(x) for x in input().split(' ')]
		for x in range(self.n_m_d[0]):
			self.matrix += [int(x) for x in input().split(' ')]

	def process_task(self):
		self.matrix.sort(reverse=True)
		target = self.matrix[0]
		step = self.n_m_d[2]
		poss = True
		opers = []
		for x in range(1, len(self.matrix)):
			a = (target - self.matrix[x]) % step
			if a:
				poss = False
				break
			else:
				opers.append((target - self.matrix[x]) // step)
		if poss:
			if opers:
				a = round(len(opers) / 2) - 1
				if a < len(opers):
					center_target = opers[a]
				else:
					center_target = opers[a - 1]
				new_ops = [abs(x - center_target) for x in opers] + [center_target]
				self.result = str(sum(new_ops))
			else:
				self.result = '0'
		else:
			self.result = '-1'

	def get_result(self):
		return self.result
Solution = CodeforcesTask289BSolution()
Solution.read_input()
Solution.process_task()
print(Solution.get_result())


(n, m, d) = map(int, input().split())

def binary_insert(lst, val):
	(left, right) = (0, len(lst))
	while left < right:
		mid = left + (right - left) // 2
		if val == lst[mid]:
			right = mid
		elif val < lst[mid]:
			right = mid
		else:
			left = mid + 1
	lst.insert(right, val)
	return lst
arr = []
mod_val = None
stop = False
for _ in range(n):
	for num in map(int, input().split()):
		if mod_val is None:
			mod_val = num % d
		if num % d != mod_val:
			stop = True
			break
		binary_insert(arr, num)
	if stop:
		print(-1)
		break
else:
	median = arr[n * m // 2]
	ans = 0
	for val in arr:
		ans += abs(median - val)
	print(ans // d)


def min_moves(l2, count=0):
	if (len(l2) - 1) % 2 == 0:
		median = l2[int((len(l2) - 1) / 2)]
	else:
		median = l2[int((len(l2) - 1) / 2) + 1]
	for i in range(1, len(l2)):
		if l2[i] % d != l2[i - 1] % d:
			return -1
	for i in range(len(l2)):
		if l2[i] < median:
			diff = median - l2[i]
			count += diff / d
		elif l2[i] > median:
			diff = l2[i] - median
			count += diff / d
	return int(count)
(n, m, d) = input().split()
n = int(n)
m = int(m)
d = int(d)
l = []
l2 = []
for i in range(n):
	l1 = list(map(int, input().split()))
	l.append(l1)
for i in range(len(l)):
	for j in range(len(l[i])):
		l2.append(l[i][j])
l2.sort()
print(min_moves(l2))


from collections import Counter
(n, m, d) = map(int, input().split())
a = []
for i in range(n):
	a += tuple(map(int, input().split()))
c = a[0] % d
ok = True
for i in a:
	if i % d != c:
		ok = False
		break
if ok:
	mx = 1e+18
	for i in range(n * m):
		ct = 0
		for j in range(n * m):
			if i != j:
				ct += abs(a[i] - a[j]) // d
		mx = min(mx, ct)
	print(mx)
else:
	print(-1)


def solve(n, m, d, ar):
	cnt = 0
	flag = True
	s = set()
	num = []
	for i in range(n):
		for j in range(m):
			if ar[i][j] % d not in s:
				s.add(ar[i][j] % d)
			num.append(ar[i][j])
	if len(s) != 1:
		print(-1)
		return
	num.sort()
	key = num[len(num) // 2]
	ans = int(1000000000.0)
	val = key
	for i in range(n):
		for j in range(m):
			if ar[i][j] == val:
				continue
			diff = abs(val - ar[i][j])
			cnt += diff // d
	ans = min(ans, cnt)
	cnt = 0
	print(ans)
(n, m, d) = map(int, input().split())
ar = []
for i in range(n):
	arr = list(map(int, input().split()))
	ar.append(arr)
solve(n, m, d, ar)


(x, y, n) = map(int, input().split())
a = []
b = []
for i in range(x):
	a += list(map(int, input().split()))
r = a[0] % n
count = 0
count1 = 0
for i in a:
	if i % n != r:
		print(-1)
		exit()
a.sort()
s = 0
x = a[x * y // 2]
for i in a:
	s += abs(x - i) // n
print(s)


def PoloMatrix(eles, n, m, d):
	x = int((n * m - 1) / 2)
	for i in range(n * m):
		y = eles[-1] - eles[i]
		if y % d != 0:
			print('-1')
			return
	ans = sum(eles[x + 1:]) - sum(eles[:x + 1])
	if n * m % 2 == 1:
		ans += eles[x]
	print(int(ans / d))
(n, m, d) = [int(x) for x in input().split()]
eles = []
for i in range(n):
	eles += [int(x) for x in input().split()]
eles1 = sorted(eles)
PoloMatrix(eles1, n, m, d)


def solve(d, l):
	l.sort()
	m = l[0] % d
	median = len(l) // 2
	res = 0
	for num in l:
		if num % d != m:
			return -1
		res += abs(num - l[median]) // d
	return res

def __starting_point():
	f = lambda : list(map(int, input().split()))
	(n, m, d) = f()
	l = []
	for i in range(n):
		l += f()
	print(solve(d, l))
__starting_point()


import sys, os, io, time, copy, math
from functools import lru_cache
if os.path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')

def main():
	(n, m, d) = map(int, input().split())
	mat = []
	for i in range(n):
		arr = list(map(int, input().split()))
		mat += arr
	mat.sort()
	median = mat[(n * m + 1) // 2 - 1]
	req = median
	if n * m % 2 != 0:
		req2 = req
	else:
		req2 = mat[(n * m + 1) // 2]
	flag = 0
	count = 0
	count2 = 0
	for m in mat:
		if abs(m - req) % d != 0:
			flag = 1
			break
		else:
			count += abs(m - req) // d
	if flag == 1:
		print(-1)
	else:
		print(count)
main()


def polo(l, d):
	l.sort()
	k = l[int(len(l) / 2)]
	s = 0
	for n in l:
		if abs(n - k) % d == 0:
			s = s + abs(n - k)
		else:
			return -1
	return int(s / d)
l = []
(n, m, d) = [int(x) for x in input().split(' ')]
for _ in range(n):
	l.extend((int(x) for x in input().split(' ')))
print(polo(l, d))


import itertools
gi = lambda : list(map(int, input().split()))
(n, m, d) = gi()
l = list(itertools.chain.from_iterable([gi() for _ in range(n)]))
l.sort()
ma = l[-1]
for e in l:
	if (ma - e) % d:
		print(-1)
		exit()
temp = l[n * m // 2]
ans = sum([abs(e - temp) for e in l]) // d
print(ans)


(n, m, d) = map(int, input().split())
a = []
for i in range(n):
	a.extend(list(map(int, input().split())))
a.sort()
k = 0
mi = n * m // 2
for i in range(n * m):
	if abs(a[mi] - a[i]) % d != 0:
		print(-1)
		return
	else:
		k += abs(a[mi] - a[i]) // d
print(k)


def fastio():
	import sys
	from io import StringIO
	from atexit import register
	global input
	sys.stdin = StringIO(sys.stdin.read())
	input = lambda : sys.stdin.readline().rstrip('\r\n')
	sys.stdout = StringIO()
	register(lambda : sys.__stdout__.write(sys.stdout.getvalue()))
fastio()
MOD = 10 ** 9 + 7
I = lambda : list(map(int, input().split()))
(n, m, d) = I()
a = []
mod = -1
for i in range(n):
	l = I()
	if mod == -1:
		mod = l[0] % d
	for j in range(m):
		if l[j] % d != mod:
			print(-1)
			exit()
		l[j] -= mod
	a += l
a.sort()
n = n * m
k = a[n // 2]
ans = 0
for i in a:
	ans += abs(k - i) // d
print(ans)


(n, m, d) = map(int, input().split())
array = []
for i in range(n):
	array.extend(map(int, input().split()))
array.sort()
mid = int(n * m / 2)
ans = 0
notpossible = False
for i in range(n * m):
	if array[mid] > array[i]:
		diff = array[mid] - array[i]
		if diff % d != 0:
			notpossible = True
			break
		ans += int(diff / d)
	elif array[mid] < array[i]:
		diff = array[i] - array[mid]
		if diff % d != 0:
			notpossible = True
			break
		ans += int(diff / d)
if notpossible:
	print('-1')
else:
	print(ans)


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
import math
(n, m, d) = map(int, input().split())
vals = []
for s in range(n):
	vals += list(map(int, input().split()))
broke = False
for s in range(1, n * m):
	if vals[s - 1] % d == vals[s] % d:
		continue
	else:
		broke = True
		break
if broke == True:
	print(-1)
else:
	vals.sort()
	med = vals[n * m // 2]
	print(sum([abs(vals[s] - med) // d for s in range(n * m)]))


(n, m, d) = list(map(int, input().split()))
no = []
min = -1
flag = 1
for _ in range(n):
	A = list(map(int, input().split()))
	for i in A:
		if flag:
			if min == -1:
				min = i
				no.append(i)
			elif abs(min - i) % d == 0:
				no.append(i)
			else:
				print(-1)
				flag = 0
				break
if flag:
	no.sort()
	middle = no[int(n * m / 2)]
	ans = 0
	for i in no:
		ans += abs(i - middle) / d
	print(int(ans))


from sys import stdin, stdout
import heapq
import cProfile
from collections import Counter, defaultdict, deque
from functools import reduce
import math

def get_int():
	return int(stdin.readline().strip())

def get_tuple():
	return map(int, stdin.readline().split())

def get_list():
	return list(map(int, stdin.readline().split()))

def solve():
	(n, m, d) = get_tuple()
	arr = []
	for _ in range(n):
		arr.extend(get_list())
	mod = arr[0] % d
	for val in arr:
		if val % d != mod:
			return -1
	arr.sort()
	median = arr[n * m // 2]
	ans = 0
	for val in arr:
		ans += abs(val - median)
	return ans // d

def main():
	print(solve())
TestCases = False
if TestCases:
	for i in range(get_int()):
		main()
else:
	main()


import math
(n, m, d) = map(int, input().split())
k = {}
flag = True

def f(x):
	answer = 0
	for i in k:
		answer += k[i] * abs(x / d - i)
	return answer
r = list(map(int, input().split()))
ost = r[0] % d
for j in r:
	if j % d != ost:
		flag = False
	elif j // d not in k:
		k[j // d] = 1
	else:
		k[j // d] += 1
for i in range(n - 1):
	r = list(map(int, input().split()))
	for j in r:
		if j % d != ost:
			flag = False
		elif j // d not in k:
			k[j // d] = 1
		else:
			k[j // d] += 1
if flag:
	l = 0
	r = 10 ** 4 + 10
	for i in range(200):
		q1 = l + (r - l) / 3
		q2 = l + 2 * (r - l) / 3
		if f(q1) < f(q2):
			r = q2
		else:
			l = q1
	print(int(f(int((l + r) / 2 + 0.1))))
else:
	print(-1)


import os
import sys
from io import BytesIO, IOBase
import math
from decimal import *
getcontext().prec = 25
from itertools import permutations
MOD = pow(10, 9) + 7
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
(n, m, k) = map(int, input().split(' '))
a = []
for i in range(n):
	l = list(map(int, input().split(' ')))
	for j in l:
		a.append(j)
a.sort()
mod = n * m // 2
val = a[mod]
ans = 0
for i in range(len(a)):
	x = abs(val - a[i])
	if x % k:
		ans = -1
		break
	else:
		ans += x // k
print(ans)


from collections import deque

def func(n, arr, d):
	arr = sorted(arr)
	median = arr[n // 2]
	res = 0
	for i in range(n):
		res += abs(median - arr[i]) // d
	print(res)
	return
(n, m, d) = list(map(int, input().split()))
temp = set()
arr = deque([])
for i in range(n):
	num = list(map(int, input().split()))
	for j in range(m):
		temp.add(num[j] % d)
		arr.append(num[j])
if len(temp) > 1:
	print(-1)
else:
	func(n * m, arr, d)


import collections, math, itertools, bisect, heapq, copy

class Solution:

	def solve(self):
		(n, m, d) = list(map(int, input().rstrip().split()))
		arr = []
		for i in range(n):
			a = list(map(int, input().rstrip().split()))
			arr += a
		arr = sorted(arr)
		mid = arr[len(arr) // 2]
		res = 0
		for num in arr:
			if (mid - num) % d != 0:
				print(-1)
				return
			res += (mid - num) // d if mid - num >= 0 else -(mid - num) // d
		print(res)
solution = Solution()
solution.solve()


(n, m, d) = map(int, input().split())
a = []
sum = 0
for i in range(n):
	a.extend(list(map(int, input().split())))
x = a[0] % d
a.sort()
mid = a[n * m // 2]
for i in a:
	if i % d != x:
		print('-1')
		exit(0)
	else:
		sum += abs(i - mid) // d
print(sum)


from math import ceil
(n, m, d) = map(int, input().split())
l = []
p = []
for i in range(n):
	g = list(map(int, input().split()))
	l.append(g)
	p += g
f = True
ans = 0
k = p[0] % d
for i in p[1:]:
	if k != i % d:
		f = False
		break
if f:
	p.sort()
	j = n * m // 2
	ans = 0
	for i in p:
		ans += abs(i - p[j]) // d
	print(ans)
else:
	print(-1)


(n, m, d) = list(map(int, input().split()))
a = []
for i in range(n):
	b = list(map(int, input().split()))
	a = a + b
a.sort()
if d > a[n * m - 1] - a[0] and a[0] != a[n * m - 1]:
	print(-1)
else:
	s = 0
	x = a[0] % d
	m = a[n * m // 2]
	for i in a:
		if i % d != x:
			print(-1)
			return
		s = s + abs(m - i) / d
	print(int(s))


(n, m, d) = [int(i) for i in input().split()]
arr = []
for i in range(n):
	arr += [int(i) for i in input().split()]
mod = arr[0] % d
count = 0
done = False
for i in range(n * m):
	if arr[i] % d != mod:
		done = True
		break
if done:
	print(-1)
else:
	arr.sort()
	median = arr[n * m // 2]
	for el in arr:
		count += abs(el - median) // d
	print(count)


from collections import Counter
import heapq
import math
(n, m, d) = map(int, input().split())
matrix = []
for i in range(n):
	matrix.extend(list(map(int, input().split())))
matrix.sort(reverse=True)
pivot = matrix[n * m // 2]
rem = pivot % d
times = 0
for i in matrix:
	if i % d == rem:
		times += abs(i - pivot) // d
	else:
		print(-1)
		break
else:
	print(times)


from sys import stdin, stdout
import math
import bisect
input = stdin.readline

def print(x='', y='', end='\n'):
	if y == '':
		stdout.write(str(x) + end)
	else:
		stdout.write(str(x) + ' ' + str(y) + end)

def solve():
	(n, m, d) = map(int, input().split())
	l = []
	for i in range(n):
		l.extend(list(map(int, input().split())))
	l.sort()
	c = l[0] % d
	for i in range(n * m):
		if l[i] % d != c:
			print(-1)
			return
	ans = 0
	minn = 10 ** 12
	for i in range(m * n):
		cur = 0
		for j in range(m * n):
			cur += abs(l[j] - l[i]) // d
		minn = min(cur, minn)
	print(minn)
tt = 1
for __ in range(tt):
	solve()


def mlt():
	return map(int, input().split())

def arp():
	return [*mlt()]
(x, y, d) = mlt()
z = []
for n in range(x):
	z += arp()
z.sort()
x = x * y
md = z[x // 2]
sm = 0
for n in z:
	sm += abs(md - n)
	if abs(md - n) % d != 0:
		print(-1)
		exit(0)
print(sm // d)


import sys
from math import *

def solve():
	(n, m, d) = map(int, input().split())
	a = []
	b = []
	x = -1
	for i in range(n):
		vals = list(map(int, input().split()))
		for v in vals:
			a.append(v)
			x = max(x, v % d)
		b.append(vals)
	a = sorted(a)
	ans = 0
	mid = a[len(a) // 2]
	x = b[0][0] % d
	for i in range(n):
		for j in range(m):
			if b[i][j] % d != x:
				print(-1)
				return 0
			ans += abs(mid - b[i][j]) // d
	print(ans)
solve()


import sys
(n, m, d) = map(int, input().split())
a = []
for _ in range(n):
	a += [int(x) for x in input().split()]
a.sort()
for i in range(n * m - 1, -1, -1):
	a[i] -= a[0]
	if a[i] % d != 0:
		print('-1')
		break
else:
	k = n * m // 2
	t = a[k]
	ans = 0
	for x in a:
		ans += abs(x - t) // d
	print(ans)


(n, m, d) = map(int, input().split())
a = []

def f(m):
	m = mod + m * d
	ans = 0
	for i in a:
		ans += abs(i - m) // d
	return ans
for i in range(n):
	a += list(map(int, input().split()))
mod = a[0] % d
for k in range(1, n * m):
	if a[k] % d != mod:
		print(-1)
		exit()
l = 0
r = 10001
while r - l > 2:
	m1 = l + (r - l) // 3
	m2 = m1 + (r - l) // 3
	a1 = f(m1)
	a2 = f(m2)
	k1 = m1 * d + mod
	k2 = m2 * d + mod
	if f(m1) >= f(m2):
		l = m1
	else:
		r = m2
print(min(f(l), f(l + 1), f(r)))


(n, m, d) = map(int, input().split())
l = [[int(j) for j in input().split()] for i in range(n)]
mas = []
a = l[0][0] % d
flag = 1
k = n * m
for i in range(n):
	for j in range(m):
		if l[i][j] % d != a:
			flag = 0
			break
		mas.append(l[i][j])
if flag == 0:
	print(-1)
else:
	mas.sort()
	t = mas[k // 2]
	su = 0
	for i in mas:
		su += abs(i - t)
	print(su // d)


(n, m, d) = list(map(int, input().split()))
a = []
c = []
for i in range(n):
	b = list(map(int, input().split()))
	for i in range(m):
		t1 = b[i] % d
		if len(a) == 0:
			a.append(t1)
			c.append(b[i] // d)
		elif t1 not in a:
			a.append(t1)
			c.append(b[i] // d)
		else:
			c.append(b[i] // d)
if len(a) >= 2:
	print(-1)
else:
	c.sort()
	t1 = len(c)
	e = 0
	if t1 % 2 != 0:
		t2 = t1 // 2
		for i in range(t1):
			t3 = c[t2] - c[i]
			if t3 < 0:
				t3 = t3 * -1
			e += t3
		print(e)
	else:
		f = 0
		t2 = t1 // 2
		t3 = t2 - 1
		for i in range(t1):
			t4 = c[t2] - c[i]
			t5 = c[t3] - c[i]
			if t4 < 0:
				t4 = t4 * -1
			if t5 < 0:
				t5 = t5 * -1
			e += t4
			f += t5
		print(min(e, f))


import sys
(n, m, d) = list(map(int, input().split()))
s = 0
a = []
for i in range(n):
	v = list(map(int, input().split()))
	a.append(v)
r1 = a[0][0] % d
f = 0
set1 = set()
for i in a:
	for j in i:
		set1.add(j)
		if j % d != r1:
			print(-1)
			f = 1
			break
	if f == 1:
		break
if f == 0:
	smin = sys.maxsize
	for vals in set1:
		s = 0
		for i in a:
			for j in i:
				s += abs(vals - j) // d
		smin = min(s, smin)
	print(smin)


from functools import reduce
import os
import sys
from collections import *
from math import *
from bisect import *
from heapq import *
from io import BytesIO, IOBase
input = lambda : sys.stdin.readline().rstrip('\r\n')

def value():
	return tuple(map(int, input().split()))

def arr():
	return [int(i) for i in input().split()]

def sarr():
	return [int(i) for i in input()]

def starr():
	return [str(x) for x in input().split()]

def inn():
	return int(input())

def svalue():
	return tuple(map(str, input().split()))

def parr():
	return [value() for i in range(n)]
mo = 1000000007
(n, m, k) = value()
l = [arr() for i in range(n)]
a = []
flag = 0
for i in range(n):
	for j in range(m):
		a += [l[i][j]]
a.sort()
mid = (len(a) - 1) // 2
ans = 0
for i in range(n * m):
	res = abs(a[i] - a[mid])
	if res % k == 0:
		ans += res // k
	else:
		flag = 1
		break
if flag == 1:
	print(-1)
else:
	print(ans)


def f(t):
	t.sort()
	return t[len(t) // 2]
(n, m, d) = map(int, input().split())
(t, p) = ([], [0] * (n * m))
for i in range(n):
	t += list(map(int, input().split()))
u = t[0] % d
for (i, v) in enumerate(t):
	if u != v % d:
		p = []
		break
	else:
		p[i] = v // d
if p:
	s = f(p)
	print(sum((abs(i - s) for i in p)))
else:
	print(-1)


(n, m, d) = map(int, input().split())
lst = []
for i in range(n):
	sublist = list(map(int, input().split()))
	for j in sublist:
		lst.append(j)
lst.sort()
mid = lst[len(lst) // 2]
ans = 0
for i in lst:
	if abs(i - mid) % d != 0:
		ans = -1
		break
	ans += abs(i - mid) // d
print(ans)


import pprint
import cmath
pp = pprint.PrettyPrinter().pprint
flag_possible = True
(n, m, d) = list(map(int, input().split()))
min_el = cmath.inf
arr_el = []
for _ in range(n):
	for el in map(int, input().split()):
		min_el = min(min_el, el)
		arr_el.append(el)
for el in arr_el:
	if (el - min_el) % d != 0:
		flag_possible = False
		break
if flag_possible:
	sorted_arr = sorted(arr_el)
	base_el = sorted_arr[len(sorted_arr) // 2]
	moves = 0
	for el in arr_el:
		moves += abs(el - base_el) // d
	print(moves)
else:
	print(-1)


import sys
(n, m, d) = list(map(int, input().split()))
s = 0
a = []
for i in range(n):
	v = list(map(int, input().split()))
	a.append(v)
r1 = a[0][0] % d
f = 0
set1 = []
for i in a:
	for j in i:
		set1.append(j)
		if j % d != r1:
			print(-1)
			f = 1
			break
	if f == 1:
		break
if f == 0:
	set1 = sorted(set1)
	median = set1[n * m // 2]
	del set1
	for i in a:
		for j in i:
			s += abs(median - j) // d
	print(s)


array = []
(n, m, d) = input().split()
(n, m, d) = (int(n), int(m), int(d))
for i in range(n):
	array += list(map(int, input().split()))
rem = array[0] % d
flag = False
for j in range(m * n):
	if array[j] % d != rem:
		flag = True
if flag:
	print('-1')
else:
	array.sort()
	median = len(array) // 2
	ans = 0
	for i in range(n * m):
		val = array[i] - array[median]
		if val < 0:
			val = -val
		ans += val
	print(ans // d)


(n, m, d) = [int(i) for i in input().split()]
matrix = []
for i in range(n):
	matrix.append([int(i) for i in input().split()])
flag = 0
start_parity = matrix[0][0] % d
ele = []
for i in range(n):
	for j in range(m):
		ele.append(matrix[i][j])
		if matrix[i][j] % d != start_parity:
			flag = 1
if flag:
	print(-1)
else:
	ans = 0
	ele.sort()
	num = len(ele)
	mid = num // 2
	target = ele[mid]
	for i in range(num):
		temp = abs(target - ele[i])
		ans += temp // d
	print(ans)


from statistics import median
(n, m, d) = map(int, input().split())
numbers = []
for _ in range(n):
	row = list(map(int, input().split()))
	numbers += row
numbers.sort()
total = 0
med = median(numbers)
for i in numbers:
	to_add = (med - i) / d
	total += abs(to_add)
print(int(total) if int(total) == total else -1)


from sys import stdin
import math
(n, m, d) = list(map(int, stdin.readline().rstrip().split(' ')))
arr = []
for r in range(n):
	for num in list(map(int, stdin.readline().rstrip().split(' '))):
		arr.append(num)
arr.sort()
diff = None
for num in arr:
	if diff is None:
		diff = num % d
	elif diff == num % d:
		continue
	else:
		print(-1)
		exit()
med = arr[len(arr) // 2]
print(sum((abs(num - med) for num in arr)) // d)


(n, m, d) = map(int, input().split())
a = []
check = 1
mark = [0 for _ in range(10001)]
ans = 1000000000
for _ in range(n):
	inn = list(map(int, input().split()))
	a = a + inn
mem = {a[0]}
total = a[0]
mark[a[0]] += 1
for i in range(1, len(a)):
	mark[a[i]] += 1
	mem.add(a[i])
	if abs(a[0] - a[i]) % d != 0:
		check = 0
		break
	else:
		total += a[i]
if check:
	for value in mem:
		mean = value
		temp = 0
		for v in mem:
			mul = mark[v]
			temp += abs(mean - v) * mul // d
			if temp > ans:
				break
		if temp < ans:
			ans = temp
print(ans if check else -1)


import sys
import bisect
import heapq
from math import *
from collections import defaultdict as dd
from collections import deque
from collections import Counter as c
from itertools import combinations as comb
from bisect import bisect_left as bl, bisect_right as br, bisect
mod = pow(10, 9) + 7
mod2 = 998244353

def data():
	return sys.stdin.readline().strip()

def out(var):
	sys.stdout.write(var)

def l():
	return list(map(int, data().split()))

def sl():
	return list(map(str, data().split()))

def sp():
	return map(int, data().split())

def ssp():
	return map(str, data().split())

def l1d(n, val=0):
	return [val for i in range(n)]

def l2d(n, m, val=0):
	return [[val for i in range(n)] for j in range(m)]
(n, m, d) = sp()
mat = list()
for i in range(n):
	arr = l()
	for j in range(m):
		mat.append(arr[j])
if len(set(mat)) == 1:
	out('0')
	exit()
mat.sort()
count = set(mat[:])
for k in count:
	answer = 0
	ele = k
	for i in mat:
		if i == ele:
			continue
		if i > ele:
			if (i - ele) % d != 0:
				out('-1')
				exit()
			answer += (i - ele) // d
		else:
			if (ele - i) % d != 0:
				out('-1')
				exit()
			answer += (ele - i) // d
	mod = min(mod, answer)
out(str(mod))
exit()


import math, string, itertools, fractions, heapq, collections, re, array, bisect, sys, copy, functools
inf = 10 ** 20
eps = 1.0 / 10 ** 10
mod = 10 ** 9 + 7
mod2 = 998244353
dd = [(-1, 0), (0, 1), (1, 0), (0, -1)]
ddn = [(-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1)]

def LI():
	return list(map(int, sys.stdin.readline().split()))

def LLI():
	return [list(map(int, l.split())) for l in sys.stdin.readlines()]

def LI_():
	return [int(x) - 1 for x in sys.stdin.readline().split()]

def LF():
	return [float(x) for x in sys.stdin.readline().split()]

def LS():
	return sys.stdin.readline().split()

def I():
	return int(sys.stdin.readline())

def F():
	return float(sys.stdin.readline())

def S():
	return input()

def pf(s):
	return print(s, flush=True)

def pe(s):
	return print(str(s), file=sys.stderr)

def JA(a, sep):
	return sep.join(map(str, a))

def JAA(a, s, t):
	return s.join((t.join(map(str, b)) for b in a))

def IF(c, t, f):
	return t if c else f

def YES(c):
	return IF(c, 'YES', 'NO')

def Yes(c):
	return IF(c, 'Yes', 'No')

def main():
	t = 1
	rr = []
	for _ in range(t):
		(n, m, d) = LI()
		aa = [LI() for _ in range(n)]
		t = []
		s = set()
		for ai in aa:
			for a in ai:
				s.add(a % d)
				t.append(a // d)
		if len(s) > 1:
			rr.append(-1)
		else:
			t.sort()
			m = t[len(t) // 2]
			rr.append(sum((abs(c - m) for c in t)))
	return JA(rr, '\n')
print(main())


(a, b, c) = map(int, input().split())
x = []
for i in range(a):
	l = list(map(int, input().split()))
	x = x + l
x.sort()
d = 0
flag = 0
med = x[a * b // 2]
for i in range(a * b):
	if i != a * b // 2:
		if abs(x[i] - med) % c != 0:
			flag = 1
			break
		else:
			d = d + abs(x[i] - med) // c
if flag == 1:
	print(-1)
else:
	print(d)


(n, m, d) = map(int, input().split())
l = []
for i in range(n):
	l.extend(list(map(int, input().split())))
if not all(((l[0] - i) % d == 0 for i in l)):
	print(-1)
	exit()
l.sort()
ans = 0
for i in l:
	ans += abs(i - l[n * m // 2]) // d
print(ans)


inp = list(map(int, input().split()))
row = inp[0]
col = inp[1]
d = inp[2]
mat = []
arr = []
for r in range(row):
	mat.append(list(map(int, input().split())))
	for c in range(col):
		arr.append(mat[r][c])
arr.sort()
if arr[0] == arr[-1]:
	print(0)
else:
	cant = False
	for i in range(1, len(arr)):
		if (arr[i] - arr[i - 1]) % d != 0:
			cant = True
			break
	if cant:
		print(-1)
	else:
		ans = 0
		target = arr[int(len(arr) / 2)]
		for i in range(len(arr)):
			ans += int(abs(target - arr[i]) / d)
		print(ans)


import itertools
(n, m, d) = map(int, input().split())
a = []
for _ in range(n):
	a += list(map(int, input().split()))
a.sort()
a = list((a[i] - a[0] for i in range(n * m)))
if any([a[i] % d != 0 for i in range(n * m)]):
	print(-1)
else:
	ps = list(itertools.accumulate(a))
	ans = [(a[i] * (i + 1) - ps[i] + (ps[n * m - 1] - ps[i]) - a[i] * (n * m - i - 1)) // d for i in range(n * m)]
	print(min(ans))


from collections import Counter
vals = [int(x) for x in input().split()]
n = vals[0]
m = vals[1]
d = vals[2]
matrix = []
count = Counter()
for _ in range(n):
	row = [int(x) for x in input().split()]
	count.update(Counter(row))
nums = sorted(count.elements())
numberToConvert = nums[n * m // 2]
result = 0
for num in nums:
	canNumBeConverted = abs(numberToConvert - num) % d == 0
	if not canNumBeConverted:
		result = -1
		break
	result += abs(numberToConvert - num) // d
print(int(result))


from sys import stdin, stdout
I = lambda : stdin.readline().strip()
read = lambda : map(int, stdin.readline().split())
(n, m, d) = read()
arr = []
for i in range(n):
	arr.extend(list(read()))
base = arr[0]
for i in arr:
	if (i - base) % d:
		print(-1)
		quit()
arr.sort()
s = n * m
Sum = 0
dev1 = dev2 = 0
if s % 2:
	median = arr[s // 2]
	for i in arr:
		Sum += abs(i - median)
else:
	(m1, m2) = (arr[s // 2 - 1], arr[s // 2])
	Sum2 = 0
	for i in arr:
		Sum += abs(i - m1)
		Sum2 += abs(i - m2)
	Sum = min(Sum, Sum2)
print(Sum // d)


(h, w, d) = input().split()
w = int(w)
h = int(h)
d = int(d)
arr = [[int(x) for x in input().split()] for y in range(h)]
arr = [ele for i in arr for ele in i]
arr.sort()
countr = 0
if len(arr) > 1:
	if len(arr) % 2 == 0:
		mid_index = int(len(arr) / 2) - 1
	else:
		mid_index = int(len(arr) / 2)
else:
	mid_index = 0
mid = arr[mid_index]
for i in range(0, len(arr)):
	if mid > arr[i]:
		diff = mid - arr[i]
		if diff % d == 0:
			countr += int(diff / d)
		else:
			countr = -1
			break
	else:
		diff = arr[i] - mid
		if diff % d == 0:
			countr += int(diff / d)
		else:
			countr = -1
			break
print(countr)


(n, m, d) = map(int, input().split())
a = []
for i in range(n):
	grid = list(map(int, input().split()))
	a = a + grid
a = sorted(a)
l = len(a)
target = a[l // 2]
count = 0
for i in range(l):
	if (target - a[i]) % d != 0:
		print(-1)
		exit()
	count += abs(a[i] - target) // d
print(count)


(n, m, d) = map(int, input().split())
matrix = []
for i in range(n):
	t = list(map(int, input().split()))
	matrix.append(t)
l = []
for j in matrix:
	for k in j:
		l.append(k)
		r = k % d
		r1 = l[0] % d
		if r == r1:
			continue
		else:
			print(-1)
			exit()
l.sort()
k = len(l)
if len(l) % 2 == 0:
	r1 = len(l) // 2
	r2 = r1 - 1
	t1 = sum(l[:r2 + 1]) - l[r2] * len(l[:r2 + 1])
	t2 = sum(l[r2 + 1:]) - l[r2] * len(l[r2 + 1:])
	k = abs(t1) + abs(t2)
	t3 = sum(l[:r1 + 1]) - l[r1] * len(l[:r1 + 1])
	t4 = sum(l[r1 + 1:]) - l[r1] * len(l[r1 + 1:])
	k1 = abs(t3) + abs(t4)
	z = min(k, k1)
	z = int(z / d)
elif len(l) % 2 == 1:
	t = len(l) // 2
	t1 = sum(l[:t]) - l[t] * len(l[:t])
	t2 = sum(l[t + 1:]) - l[t] * len(l[t + 1:])
	z = abs(t1) + abs(t2)
	z = int(z / d)
print(z)


(n, m, d) = map(int, input().split())
nums = []
for i in range(n):
	nums += list(map(int, input().split()))
dif = nums[0] % d
for n in nums[1:]:
	if n % d != dif:
		print(-1)
		exit()
nums = sorted(nums)
med = nums[len(nums) // 2]

def test(nums, key):
	count = 0
	for num in nums:
		count += abs(num - key) // d
	return count
print(test(nums, med))


from sys import stdin
stdin.readline

def mp():
	return list(map(int, stdin.readline().strip().split()))

def it():
	return int(stdin.readline().strip())
from math import pi
(n, m, d) = mp()
v = []
s = set()
for _ in range(n):
	v.extend(mp())
v.sort()
k = v[m * n // 2]
ans = 0
for i in range(len(v)):
	if abs(v[i] - k) % d:
		print(-1)
		exit()
	else:
		ans += abs(v[i] - k)
print(ans // d)


from collections import Counter
(n, m, d) = map(int, input().split())
a = []
for i in range(n):
	a += tuple(map(int, input().split()))
c = a[0] % d
ok = True
for i in a:
	if i % d != c:
		ok = False
		break
if ok:
	a.sort()
	m1 = a[n * m // 2]
	m2 = a[(n * m - 1) // 2]
	ct1 = 0
	ct2 = 0
	for i in range(n * m):
		ct1 += abs(m1 - a[i]) // d
		ct2 += abs(m2 - a[i]) // d
	print(min(ct1, ct2))
else:
	print(-1)


from collections import Counter
I = lambda : map(int, input().split())
(n, _, d) = I()
c = Counter()
for _ in range(n):
	c.update(I())
if len(set((a % d for a in c))) > 1:
	print(-1)
else:
	(w, s) = (0, sum(c.values()) / 2)
	for (x, k) in sorted(c.items()):
		w += k
		if w >= s:
			print(sum((k * abs(a - x) // d for (a, k) in c.items())))
			break


import sys
inf = float('inf')
mod = 1000000007

def get_array():
	return list(map(int, sys.stdin.readline().split()))

def get_ints():
	return map(int, sys.stdin.readline().split())

def input():
	return sys.stdin.readline()

def main():
	(n, m, d) = get_ints()
	mat = []
	for i in range(n):
		mat.extend(get_array())
	check = mat[0] % d
	for i in range(n * m):
		if mat[i] % d != check:
			print(-1)
			return
	mat.sort()
	median = mat[n * m // 2]
	ans = 0
	for i in range(n * m):
		ans += abs(mat[i] - median)
	print(ans // d)
main()


from math import *
(n, m, d) = map(int, input().split())
l = []
for i in range(n):
	l.extend(list(map(int, input().split())))
x = inf
for i in range(n * m):
	c = 0
	for j in range(n * m):
		c += abs(l[j] - l[i])
	x = min(c, x)
if x % d == 0:
	print(x // d)
else:
	print(-1)


def med(list):
	nonlocal n, m
	s = sorted(list)
	return s[(n * m - 1) // 2]
nmd = list(input().split())
n = int(nmd[0])
m = int(nmd[1])
d = int(nmd[2])
sum = 0
a = [[0] * m for _ in range(n)]
for i in range(n):
	a[i] = [int(j) for j in input().strip().split(' ')]
sum = 0
w = []
for i in range(n):
	for j in range(m):
		w.append(a[i][j])
k = med(w)
for i in range(n):
	for j in range(m):
		sum = sum + abs(a[i][j] - k)
		w.append(a[i][j])
if sum % d == 0:
	print(sum // d)
else:
	print(-1)


(n, m, d) = list(map(int, input().split()))
a = [[0] * m for i in range(n)]
for i in range(n):
	s = list(map(int, input().rstrip().split()))
	for j in range(m):
		a[i][j] = s[j]
ans = float('inf')
flag = 0
arr = []
for i in range(n):
	for j in range(m):
		arr.append(a[i][j])
arr.sort()
for i in range(1, n * m):
	if (arr[i] - arr[i - 1]) % d != 0:
		flag = 1
		break
if flag == 1:
	print(-1)
else:
	count = 0
	f = n * m // 2
	ans = 0
	for i in range(n * m):
		count += abs(arr[i] - arr[f]) // d
	print(count)


import re
import itertools
from collections import Counter, deque

class Task:
	a = []
	d = 0
	answer = 0

	def getData(self):
		(n, m, self.d) = [int(x) for x in input().split(' ')]
		for _ in range(n):
			self.a += [int(x) for x in input().split(' ')]

	def solve(self):
		a = self.a
		for x in a:
			if x % self.d != a[0] % self.d:
				self.answer = -1
				return
		a = [x // self.d for x in a]
		a.sort()
		d = [sum(a)] + [0 for _ in range(1, a[-1] + 1)]
		lessCurrentLevel = 0
		counter = Counter(a)
		for level in range(1, a[-1] + 1):
			lessCurrentLevel += counter[level - 1]
			d[level] = d[level - 1] + lessCurrentLevel - (len(a) - lessCurrentLevel)
		self.answer = min(d)

	def solve2(self):
		(a, d) = (self.a, self.d)
		for i in range(1, len(a)):
			if a[i] % d != a[0] % d:
				self.answer = -1
				return
		a = [x // d for x in a]
		d = [abs(a[0] - i) for i in range(10000 + 1)]
		for i in range(1, len(a)):
			for j in range(0, len(d)):
				d[j] += abs(a[i] - j)
		self.answer = min(d)

	def printAnswer(self):
		print(self.answer)
task = Task()
task.getData()
task.solve()
task.printAnswer()


def main():
	(n, m, d) = map(int, input().split())
	entries = []
	for i in range(n):
		entries.extend(list(map(int, input().split())))
	residues = [entry % d for entry in entries]
	if residues.count(residues[0]) != len(residues):
		return -1
	entries.sort()
	median = entries[m * n // 2]
	min_moves = sum([abs(entry - median) // d for entry in entries])
	return min_moves
print(main())


(nr, nc, d) = map(int, input().split())
mat = []
l1 = []
for _ in range(nr):
	l = list(map(int, input().split()))
	l1 += l
	mat.append(l)
l1.sort()
n = nr * nc
temp = 0
m = 0
x = l1[n // 2]
for i in range(nr):
	for j in range(nc):
		if abs(mat[i][j] - x) % d == 0:
			m += abs(mat[i][j] - x) // d
		else:
			print(-1)
			temp = 1
			break
	if temp == 1:
		break
if temp == 0:
	print(m)


(n, m, d) = map(int, input().split())
mt = []
for i in range(n):
	mt += list(map(int, input().split()))
me = min(mt)
mtc = mt.copy()
if len(set(mt)) == 1:
	print(0)
else:
	com = mt[0] % d
	neg = False
	for i in range(1, len(mtc)):
		if mtc[i] % d != com:
			neg = True
			break
	if neg:
		print(-1)
	else:
		max_ct = 99999999
		for i in range(n * m):
			ct = 0
			for j in range(n * m):
				ct += abs((mt[j] - mt[i]) // d)
			max_ct = min(max_ct, ct)
		print(max_ct)


(n, m, d) = map(int, input().split())
ans = []
hola = {}
flag = 0
for i in range(n):
	l = list(map(int, input().split()))
	for j in l:
		ans.append(j)
flag = 0
ans.sort()
med = ans[len(ans) // 2]
sum = 0
for i in range(len(ans)):
	if abs((med - ans[i]) % d == 0):
		sum += abs(med - ans[i])
	else:
		flag = 1
		break
if flag != 1:
	print(sum // d)
else:
	print(-1)


(n, m, d) = map(int, input().split())
b = []
for i in range(n):
	b.extend(list(map(int, input().split())))
b.sort()
ans = float('inf')
for i in range(n * m):
	temp = 0
	for j in range(n * m):
		temp += abs(b[i] - b[j])
	ans = min(ans, temp)
print(ans // d if ans % d == 0 else -1)


(a, b, c) = map(int, input().split())
l = []
p = True
for i in range(a):
	l += list(map(int, input().split()))
l.sort()
s = l[a * b // 2]
cc = 0
for i in l:
	k = abs(i - s)
	if k % c == 0:
		cc += k // c
	else:
		print(-1)
		p = False
		break
if p:
	print(cc)


x = input().split(' ')
a = int(x[0])
b = int(x[1])
c = int(x[2])
d = []
i = 0
while i < a:
	e = input().split(' ')
	j = 0
	while j < b:
		d.append(int(e[j]))
		j += 1
	i += 1
l = len(d)
d = sorted(d)
i = 1
g = 0
h = []
while i < l:
	f = int(d[i]) - int(d[i - 1])
	if f % c != 0:
		g = 1
		break
	h.append(f // c)
	i += 1
if g == 1:
	print(-1)
else:
	m = 0
	k = len(h)
	i = 0
	n = 0
	while i < k:
		m = m + n + h[i]
		n = n + h[i]
		i += 1
	o = m
	i = 1
	p = m
	q = 0
	while i < k:
		j = 0
		n = 0
		while j < i:
			n = n + h[j]
			j += 1
		m = o - (k - i) * n
		j = 0
		q = 0
		while j < i:
			q = q + h[j]
			m = m - q
			j += 1
		j = i - 1
		q = 0
		while j >= 0:
			q = q + h[j]
			m = m + q
			j -= 1
		p = min(m, p)
		i += 1
	print(p)


(n, m, d) = map(int, input().split())
nums = []
for i in range(n):
	nums += list(map(int, input().split()))
dif = nums[0] % d
for n in nums[1:]:
	if n % d != dif:
		print(-1)
		exit()
nums = sorted(nums)
med = nums[len(nums) // 2]

def test(nums, key):
	count = 0
	for num in nums:
		count += abs(num - key) // d
	return count

def ternarySearch(l, r, arr):
	left = l
	right = r
	while right - left > 2:
		m1 = left + (right - left) // 3
		m2 = right - (right - left) // 3
		f1 = test(nums, arr[m1])
		f2 = test(nums, arr[m2])
		if f1 > f2:
			left = m1
		else:
			right = m2
	return (left, right)
l = min(nums)
r = max(nums)
arr = [l + d * x for x in range(r // d)]
l = 0
r = len(arr) - 1
(l, r) = ternarySearch(l, r, arr)
min = 9999999999999
for i in range(l, r + 1):
	cur = test(nums, arr[i])
	if cur < min:
		min = cur
print(min)


from io import BytesIO, IOBase
from math import sqrt
import sys, os
from os import path
inpl = lambda : list(map(int, input().split()))
inpm = lambda : map(int, input().split())
inpi = lambda : int(input())
inp = lambda : input()
(rev, ra, l) = (reversed, range, len)
P = print
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))

def input():
	return sys.stdin.readline().rstrip('\r\n')

def B(n):
	return bin(n).replace('0b', '')

def factors(n):
	arr = []
	for i in ra(2, int(sqrt(n)) + 1):
		if n % i == 0:
			arr.append(i)
			if i * i != n:
				arr.append(int(n / i))
	return arr

def dfs(arr, n):
	pairs = [[i + 1] for i in ra(n)]
	vis = [0] * (n + 1)
	for i in ra(l(arr)):
		pairs[arr[i][0] - 1].append(arr[i][1])
	pairs[arr[i][1] - 1].append(arr[i][0])
	comp = []
	for i in ra(n):
		stack = [pairs[i]]
		temp = []
		if vis[stack[-1][0]] == 0:
			while len(stack) > 0:
				if vis[stack[-1][0]] == 0:
					temp.append(stack[-1][0])
					vis[stack[-1][0]] = 1
					s = stack.pop()
					for j in s[1:]:
						if vis[j] == 0:
							stack.append(pairs[j - 1])
				else:
					stack.pop()
			comp.append(temp)
	return comp
from bisect import bisect_left as bl
from bisect import bisect_right as br
import sys, operator, math, operator
from collections import Counter
if path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
import random
(n, m, d) = inpm()
li = []
for i in ra(n):
	li.extend(inpl())
li.sort()
tr = True
for i in ra(1, l(li)):
	if (li[i] - li[i - 1]) % d != 0:
		tr = False
		break
if tr:
	med = li[l(li) >> 1]
	ans = 0
	for i in ra(l(li)):
		ans += abs(med - li[i]) / d
	P(int(ans))
else:
	P(-1)


s = input().split()
(n, m, d) = (int(s[0]), int(s[1]), int(s[2]))
l = []
for i in range(n):
	for i in map(int, input().split()):
		l.append(i)
a = sorted(l)
median = a[n * m // 2]
s = 0
for i in l:
	s += abs(i - median)
if s % d == 0:
	print(s // d)
else:
	print(-1)


(n, m, d) = [int(i) for i in input().split()]
matrix = []
for i in range(n):
	arr = [int(i) for i in input().split()]
	matrix += arr
x = matrix[0] % d
ter_count = 0
for i in range(len(matrix)):
	if matrix[i] % d == x:
		ter_count += 1
if ter_count == len(matrix):
	matrix.sort()
	size = len(matrix)
	median = size // 2
	ans = 0
	for i in range(size):
		ans += abs(matrix[i] - matrix[median]) // d
	print(ans)
else:
	print(-1)


(n, m, d) = map(int, input().split())
l = []
for i in range(n):
	l.extend(list(map(int, input().split())))
l.sort()
m = l[m * n // 2]
s = 0
f = 0
for i in l:
	if abs(i - m) % d != 0:
		f = 1
		print(-1)
		break
	s += abs(i - m) // d
if not f:
	print(s)


(n, m, d) = map(int, input().split())
a = []
for _ in range(n):
	a.append(list(map(int, input().split())))
b = []
for i in a:
	b += i
b.sort()
z = b[n * m // 2]
flag = 0
ans = 0
for i in range(n * m):
	if abs(z - b[i]) % d != 0:
		flag = 1
		break
	else:
		ans += abs(z - b[i]) // d
if flag == 1:
	print(-1)
else:
	print(ans)


(n, m, d) = map(int, input().split())
mat = []
for i in range(n):
	mat.append(list(map(int, input().split())))
temp = []
for i in range(n):
	temp.extend(mat[i])
temp.sort()
rem = set()
for elem in temp:
	rem.add(elem % d)
if len(rem) > 1:
	print(-1)
else:
	ans = 0
	median = temp[n * m // 2]
	for elem in temp:
		ans += abs(elem - median)
	print(ans // d)


import sys, os.path
from collections import *
from copy import *
import math
mod = 10 ** 9 + 7
if os.path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')

def check(a):
	p = a[0]
	for i in range(1, n * m):
		b = abs(p - a[i])
		if b % d != 0:
			return 0
	return 1
(n, m, d) = map(int, input().split())
a = []
for i in range(n):
	l = list(map(int, input().split()))
	a.extend(l)
if check(a):
	fix = 0
	sum1 = sys.maxsize
	temp = 0
	for i in range(n * m):
		fix = a[i]
		for j in range(n * m):
			temp += abs(fix - a[j]) // d
		sum1 = min(sum1, temp)
		temp = 0
	print(sum1)
else:
	print(-1)


import sys
from math import *
import threading
from itertools import count
from pprint import pprint
from collections import defaultdict
from heapq import heapify, heappop, heappush
sys.setrecursionlimit(300000)
mod = 10 ** 9 + 7
inf = 10 ** 15
decision = ['NO', 'YES']
yes = 'YES'
no = 'NO'
import os
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def npr(n, r):
	return factorial(n) // factorial(n - r) if n >= r else 0

def ncr(n, r):
	return factorial(n) // (factorial(r) * factorial(n - r)) if n >= r else 0

def lower_bound(li, num):
	answer = -1
	start = 0
	end = len(li) - 1
	while start <= end:
		middle = (end + start) // 2
		if li[middle] >= num:
			answer = middle
			end = middle - 1
		else:
			start = middle + 1
	return answer

def upper_bound(li, num):
	answer = -1
	start = 0
	end = len(li) - 1
	while start <= end:
		middle = (end + start) // 2
		if li[middle] <= num:
			answer = middle
			start = middle + 1
		else:
			end = middle - 1
	return answer

def abs(x):
	return x if x >= 0 else -x

def binary_search(li, val):
	ans = -1
	lb = 0
	ub = len(li) - 1
	while lb <= ub:
		mid = (lb + ub) // 2
		if li[mid] > val:
			ub = mid - 1
		elif val > li[mid]:
			lb = mid + 1
		else:
			ans = mid
			break
	return ans

def kadane(x):
	sum_so_far = 0
	current_sum = 0
	for i in x:
		current_sum += i
		if current_sum < 0:
			current_sum = 0
		else:
			sum_so_far = max(sum_so_far, current_sum)
	return sum_so_far

def pref(li):
	pref_sum = [0]
	for i in li:
		pref_sum.append(pref_sum[-1] + i)
	return pref_sum

def SieveOfEratosthenes(n):
	prime = [True for i in range(n + 1)]
	p = 2
	li = []
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	for p in range(2, len(prime)):
		if prime[p]:
			li.append(p)
	return li

def primefactors(n):
	factors = []
	while n % 2 == 0:
		factors.append(2)
		n //= 2
	for i in range(3, int(sqrt(n)) + 1, 2):
		while n % i == 0:
			factors.append(i)
			n //= i
	if n > 2:
		factors.append(n)
	return factors

def prod(li):
	ans = 1
	for i in li:
		ans *= i
	return ans
for _ in range(1):
	(n, m, d) = map(int, input().split())
	a = []
	for i in range(n):
		a += list(map(int, input().split()))
	a.sort()
	elem = a[n * m // 2]
	f = 0
	ans = 0
	for i in range(n * m):
		if abs(a[i] - elem) % d:
			f = 1
		ans += abs(a[i] - elem)
	if f:
		print(-1)
	else:
		print(ans // d)


import io, sys, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

def printArr(arr):
	sys.stdout.write(' '.join(map(str, arr)) + '\n')

def solve(arr, n, mod):
	arr.sort()
	leftMedian = n // 2 - 1
	rightMedian = n // 2
	remainder = arr[0] % mod
	answer = 0
	answer2 = 0
	for i in range(n):
		if arr[i] % mod != remainder:
			return -1
		answer += abs(arr[leftMedian] - arr[i]) // mod
		answer2 += abs(arr[rightMedian] - arr[i]) // mod
	return min(answer, answer2)
t = 1
while t > 0:
	s = input().decode().strip().split()
	(n, m, d) = (int(s[0]), int(s[1]), int(s[2]))
	arr = list()
	for i in range(n):
		temp = [int(i) for i in input().decode().strip().split()]
		arr.extend(temp)
	answer = solve(arr, n * m, d)
	sys.stdout.write(str(answer) + '\n')
	t -= 1


from math import factorial
(n, m, d) = [int(x) for x in input().split(' ')]
nums = []
for i in range(n):
	row = [int(x) for x in input().split(' ')]
	nums += row
nums.sort()
exist = True
for i in range(1, n * m):
	if abs(nums[i] - nums[i - 1]) % d != 0:
		exist = False
		break
if not exist:
	print(-1)
else:
	answer = 0
	med = nums[len(nums) // 2]
	for i in range(n * m):
		answer += abs(med - nums[i]) // d
	print(answer)


(n, m, d) = map(int, input().split())
mat = []
for _ in range(n):
	for x in list(map(int, input().split())):
		mat.append(x)
x = mat[0] % d
for y in mat:
	if y % d != x:
		print(-1)
		exit(0)
mat = [(y - x) / d for y in mat]
mat.sort()
med = mat[int(m * n / 2)]
print(int(sum([abs(y - med) for y in mat])))


o = [*map(int, input().split())]
list1 = []
y = 0
for i in range(o[0]):
	k = [*map(int, input().split())]
	for j in k:
		list1.append(j)
list2 = sorted(list1)
nes = o[1] * o[0] // 2
for z in range(len(list2)):
	if (list2[nes] - list2[z]) % o[2] != 0:
		print(-1)
		exit(0)
	else:
		y += abs(list2[nes] - list2[z]) // o[2]
print(abs(int(y)))


import math
import sys
(n, m, t) = map(int, input().split())
d = []
for i in range(n):
	d += list(map(int, input().split()))
d.sort()
r = 0
for i in range(len(d) // 2):
	if (d[len(d) - i - 1] - d[i]) % t == 0:
		r += (d[len(d) - i - 1] - d[i]) // t
	else:
		print(-1)
		exit()
print(r)


(n, m, d) = map(int, input().strip().split())
lis = []
for _ in range(n):
	l = list(map(int, input().strip().split()))
	lis.extend(l)
lis.sort()
mid = n * m // 2
flag = 0
count = 0
for x in range(n * m):
	if abs(lis[x] - lis[0]) % d != 0:
		print('-1')
		flag = 1
		break
	else:
		count += abs(lis[x] - lis[mid]) // d
if flag == 0:
	print(count)


(n, m, k) = [int(x) for x in input().split()]
temp = []
for _ in range(n):
	arr = [int(x) for x in input().split()]
	for i in arr:
		temp.append(i)
temp.sort()
f = True
mid = temp[n * m // 2]
ans = 0
for i in temp:
	if abs(mid - i) % k:
		f = False
		break
	else:
		ans += abs(mid - i) // k
if f == False:
	print(-1)
else:
	print(ans)


(n, m, d) = map(int, input().split())
a = []
for i in range(n):
	a.extend(map(int, input().split()))
a.sort()
n = len(a)
an = 0
j = a[n // 2]
for i in a:
	t = abs(i - j)
	if t % d:
		an = -1
		break
	else:
		an += t // d
print(an)


(n, m, d) = map(int, input().split())
k = []
for i in range(n):
	[k.append(i) for i in list(map(int, input().split()))]
k.sort()
middle = len(k) // 2
c = 0
for i in range(len(k)):
	if abs(k[middle] - k[i]) % d != 0:
		c = -1
		break
	else:
		c += abs(k[middle] - k[i]) // d
print(c)


import sys
import time
import os
from math import sqrt, log, log2, ceil, log10, gcd, floor, pow, sin, cos, tan, pi, inf, factorial
from copy import copy, deepcopy
from sys import exit, stdin, stdout
from collections import Counter, defaultdict, deque
from itertools import permutations
import heapq
from bisect import bisect_left as bl
from bisect import bisect_right as br
from bisect import bisect
mod = 1000000007
iinp = lambda : int(sys.stdin.readline())
inp = lambda : sys.stdin.readline().strip()
strl = lambda : list(inp().strip().split(' '))
intl = lambda : list(map(int, inp().split(' ')))
mint = lambda : map(int, inp().split())
flol = lambda : list(map(float, inp().split(' ')))
flush = lambda : stdout.flush()

def solve():
	(n, m, d) = mint()
	oldmat = [intl() for i in range(n)]
	newmat = []
	for i in oldmat:
		for j in i:
			newmat.append(j)
	newmat.sort()
	k = newmat[0] % d
	for x in newmat:
		if x % d != k:
			print(-1)
			return
	comp = newmat[n * m // 2]
	sm = 0
	for i in newmat:
		dif = abs(comp - i)
		sm += dif // d
	print(sm)
t = 1
for _ in range(t):
	solve()


import sys

def input():
	return sys.stdin.readline().strip()

def iinput():
	return int(input())

def rinput():
	return map(int, sys.stdin.readline().strip().split())

def get_list():
	return list(map(int, sys.stdin.readline().strip().split()))
(n, m, d) = rinput()
a = []
s = []
for i in range(n):
	s.append(list(map(int, input().split())))
for i in range(n):
	for j in range(m):
		a.append(s[i][j])
ans = 0
a.sort()
k = int(m * n)
for i in range(k):
	if a[i] != a[k // 2]:
		ans += abs(a[i] - a[k // 2])
if ans % d == 0:
	print(ans // d)
else:
	print(-1)


(n, m, d) = list(map(int, input().split()))
l = []
for i in range(n):
	l.append(list(map(int, input().split())))
a = []
for i in range(n):
	for j in range(m):
		a.append(l[i][j])
a.sort()
f = 1
w = [0]
for i in range(1, len(a)):
	if (a[i] - a[i - 1]) % d != 0:
		f = 0
		break
	else:
		w.append(a[i] - a[i - 1])
if f:
	r = [0] * len(w)
	e = [0] * len(w)
	for i in range(1, len(w)):
		e[i] = w[i] * i + e[i - 1]
	for i in range(len(w) - 2, -1, -1):
		r[i] = w[i + 1] * (len(w) - 1 - i) + r[i + 1]
	c = 879878998
	for i in range(len(w)):
		c = min(c, (e[i] + r[i]) // d)
	print(c)
else:
	print(-1)


from sys import stdin, stdout
from math import gcd
ii1 = lambda : int(stdin.readline().strip())
is1 = lambda : stdin.readline().strip()
iia = lambda : list(map(int, stdin.readline().strip().split()))
isa = lambda : stdin.readline().strip().split()
mod = 1000000007
(n, m, d) = iia()
arr = []
for _ in range(n):
	arr.extend(iia())
arr.sort()
num = arr[len(arr) // 2]
res = 0
for i in range(len(arr)):
	if arr[i] != num:
		if abs(arr[i] - num) % d == 0:
			res += abs(arr[i] - num) // d
		else:
			print(-1)
			break
else:
	print(res)


(n, m, d) = map(int, input().split())
f = 1
mat = []
ans = 0
l1 = []
mini = 10 ** 7
for i in range(n):
	l = [int(i) for i in input().split()]
	l1 += l
	mini = min(mini, min(l))
	mat.append(l)
l1.sort()
med = l1[len(l1) // 2]
for i in range(n):
	for j in range(m):
		curr = mat[i][j]
		if abs(curr - med) % d == 0:
			ans += abs(curr - med) // d
		else:
			f = 0
if f:
	print(ans)
else:
	print(-1)


a = input().split(' ')
n = int(a[0])
m = int(a[1])
d = int(a[2])
total = 0
X = []
for i in range(n):
	a = input().split(' ')
	for j in a:
		y = int(j)
		X.append(y)
X.sort()
median = X[int(n * m / 2)]
for i in range(n * m):
	y = X[i]
	diff = abs(median - y)
	if diff % d != 0:
		total = -1
		break
	else:
		total += int(diff / d)
print(str(total))


from sys import *
input = stdin.readline
(n, m, d) = map(int, input().split())
l = []
for _ in range(n):
	h = list(map(int, input().split()))
	l.extend(h)
k = l[0] % d
c = 0
for i in range(n * m):
	if l[i] % d != k:
		print(-1)
		c = -1
		break
if c == 0:
	l.sort()
	median = l[(n * m - 1) // 2]
	for i in l:
		c += abs(i - median) // d
	print(c)


import math
(n, m, d) = map(int, input().split())
matrix = [[] for _ in range(n)]
for row in range(n):
	matrix[row] = list(map(int, input().split()))
all = []
for r in range(n):
	for c in range(m):
		all.append(matrix[r][c])
mod_d = all[0] % d
ok = not any((x for x in all if x % d != mod_d))
if not ok:
	print(-1)
else:
	all.sort()
	target = all[len(all) // 2]
	res = 0
	for i in range(len(all)):
		res += abs(target - all[i]) // d
	print(res)


while True:
	try:

		def solution(len, res, d):
			mid = 0
			if len % 2 == 0:
				mid = len // 2
			else:
				mid = len // 2 + 1
			ans = 0
			valid = True
			for i in range(len):
				if res[i] != res[mid - 1]:
					tem = abs(res[mid - 1] - res[i])
					if tem % d != 0:
						valid = False
					if not valid:
						break
					ans += tem // d
			if not valid:
				print('-1')
			else:
				print(ans)

		def read():
			(n, m, d) = map(int, input().split())
			res = list()
			for i in range(n):
				temp = list(map(int, input().split()))
				for j in range(m):
					res.append(temp[j])
				del temp
			res.sort()
			solution(n * m, res, d)
		if __name__ == '__main__':
			read()
	except EOFError:
		break


import statistics
import sys
(n, m, d) = input().split()
if n == 1 and m == 1:
	print('0')
else:
	a = [[0] * int(m)] * int(n)
	for i in range(int(n)):
		a[i] = [int(x) for x in input().split()]
	k = []
	l = []
	for i in range(int(n)):
		for j in range(int(m)):
			k.append(a[i][j])
			l.append(a[i][j] % int(d))
	if len(list(set(l))) != 1:
		print('-1')
	else:
		z = statistics.median(k)
		r = int(z / int(d))
		r1 = r * int(d) + int(l[0])
		step = 0
		for i in range(len(k)):
			if r1 - k[i] >= 0:
				abs = r1 - k[i]
			else:
				abs = k[i] - r1
			step = step + abs
		print(int(step / int(d)))


import sys
import math
(n, m, d) = map(int, input().split())
(mata, suma, flag, usum, lsum) = ([], 0, True, 0, 0)
for i in range(n):
	ina = [int(x) for x in input().strip().split()]
	sume = sum(ina)
	suma += sume
	mata.extend(ina)
mata = sorted(mata)
diva = mata[0] % d
mavg = mata[len(mata) // 2]
for i in range(n * m):
	if mata[i] % d != diva:
		flag = False
		break
	else:
		lsum += abs(mata[i] - mavg) // d
if flag == True:
	print(lsum)
else:
	print('-1')


from itertools import chain
(n, m, d) = map(int, input().split())
a = [map(int, input().split()) for i in range(n)]
p = sorted(chain.from_iterable(a))
e = set()
ans = 0
for i in p:
	e.add(i % d)
if len(e) > 1:
	print(-1)
	exit()
elif len(p) % 2 == 0:
	med = p[len(p) // 2 - 1]
	for i in p:
		ans += abs(i - med)
	print(ans // d)
else:
	med = p[len(p) // 2]
	for i in p:
		ans += abs(i - med)
	print(ans // d)


(n, m, d) = map(int, input().split())
a = []
b = []
for i in range(n):
	tmp = list(map(int, input().split()))
	a.append(tmp)
	b = b + tmp
flag = True
x = a[0][0] % d
for i in range(n):
	for j in range(m):
		if a[i][j] % d != x:
			flag = False
			break
b.sort()
k = len(b)
k = k // 2
s = 0
for i in b:
	s += abs(i - b[k])
s /= d
if flag:
	print(int(s))
else:
	print(-1)


(n, m, d) = list(map(int, input().rstrip().split()))
mat = []
for _ in range(n):
	mat += list(map(int, input().rstrip().split()))
mat.sort()
if n * m == 1:
	print(0)
else:
	flag = 1
	for i in range(n * m - 1):
		if (mat[i + 1] - mat[i]) % d != 0:
			flag = 0
			break
	if flag == 0:
		print(-1)
	else:
		if n * m % 2 == 1:
			median = mat[n * m // 2]
		else:
			median = 0.5 * (mat[n * m // 2] + mat[n * m // 2 - 1])
		add = 0
		for x in mat:
			add += abs(x - median)
		ans = int(add // d)
		print(ans)


import statistics

def solve(array, d):
	minval = min(array)
	for i in range(len(array)):
		if (array[i] - minval) % d:
			return -1
		array[i] //= d
	median = round(statistics.median(array))
	moves = 0
	for el in array:
		moves += abs(el - median)
	return moves
line = input()
(n, m, d) = map(int, line.strip().split())
array = []
for i in range(n):
	line = input()
	row = list(map(int, line.strip().split()))
	array += row
print(solve(array, d))


(n, m, d) = map(int, input().split())
x = []
y = []
for i in range(n):
	a = list(map(int, input().split()))
	y += a
	x.append(a)
y.sort()
e = y[(0 + n * m - 1) // 2]
a = x[0][0] % d
count = 0
ans = 0
for i in x:
	for j in range(len(i)):
		if i[j] % d != a:
			pass
		else:
			count += 1
			ans += (max(i[j], e) - min(i[j], e)) // d
if count == n * m:
	print(ans)
else:
	print(-1)


(n, m, d) = map(int, input().split())
total = 0
grid = []
for i in range(n):
	grid.extend(list(map(int, input().split())))
grid.sort()
t = sum((abs(el - grid[n * m // 2]) for el in grid)) // d
print(t if len(set((el % d for el in grid))) <= 1 else -1)


def solve():
	(row, col, n) = list(map(int, input().split(' ')))
	arr = []
	for i in range(row):
		arr += list(map(int, input().split(' ')))
	arr.sort()
	if len(arr) == 1:
		print(0)
		return
	for i in range(len(arr) - 1):
		if (arr[i + 1] - arr[i]) % n != 0:
			print(-1)
			return
	r = len(arr) - 1
	l = 0
	total = 0
	while l < r:
		total += (arr[l + 1] - arr[l]) // n * (l + 1)
		arr[l] = arr[l + 1]
		total += (arr[r] - arr[r - 1]) // n * (len(arr) - r)
		arr[r] = arr[r - 1]
		l += 1
		r -= 1
	print(total)
solve()


(n, m, d) = map(int, input().split())
a = [0]
for i in range(n):
	a += list(map(int, input().split()))
a.sort()
s = set()
for i in range(1, len(a)):
	s.add(a[i] % d)
if len(s) >= 2:
	print(-1)
	exit()
aa = [0] * (n * m + 1)
for i in range(1, n * m + 1):
	aa[i] = aa[i - 1] + a[i]
ans = 10 ** 18
for i in range(1, n * m + 1):
	ans = min(ans, (aa[-1] - 2 * aa[i] - (n * m - 2 * i) * a[i]) // d)
print(ans)


import sys

def main():
	(n, m, d) = list(map(int, sys.stdin.readline().split(' ')))
	nums = []
	for i in range(n):
		nums = nums + list(map(int, sys.stdin.readline().split(' ')))
	k = n * m
	g = nums[0] % d
	for i in range(1, k):
		if nums[i] % d != g:
			sys.stdout.write('-1\n')
			return
	nums = sorted(nums)
	ret = 0
	median = nums[k // 2]
	for i in range(k):
		ret += abs((nums[i] - median) // d)
	sys.stdout.write('{}\n'.format(ret))
main()


(n, m, d) = map(int, input().split())
aij = list(map(int, input().split()))
for i in range(1, n):
	aij += list(map(int, input().split()))
aij.sort()
ans = 0
mod = aij[0] % d
nm = n * m
temp = 0
temp2 = 0
num = aij[nm // 2] // d
num2 = aij[nm // 2 - 1] // d
for i in range(nm):
	if mod != aij[i] % d:
		ans = -1
		break
	temp += abs(num - aij[i] // d)
	temp2 += abs(num2 - aij[i] // d)
if ans != -1:
	ans = min(temp, temp2)
print(ans)


def solve():
	(n, m, d) = map(int, input().split())
	a = []
	l = list(map(int, input().split()))
	thismod = l[0] % d
	for i in range(m):
		a.append(l[i])
		if l[i] % d != thismod:
			return -1
	for i in range(1, n):
		l = list(map(int, input().split()))
		for j in range(m):
			a.append(l[j])
			if l[j] % d != thismod:
				return -1
	a.sort()
	target = a[n * m // 2]
	score = 0
	for i in range(n * m):
		score += abs(a[i] - target) / d
	return int(score)
print(solve())


(n, m, d) = map(int, input().split())
a = []
for i in ' ' * n:
	a += list(map(int, input().split()))
a.sort()
mid = a[n * m // 2]
c = 0
for i in a:
	x = abs(i - mid)
	if x % d != 0:
		print(-1)
		exit(0)
	c += x // d
print(c)


import math
(n, m, d) = list(map(int, input().split()))
a = []
b = []
odd = True
for i in range(n):
	temp = list(map(int, input().split()))
	for j in temp:
		a.append(j)
		b.append(j % d)
if len(set(b)) != 1:
	print(-1)
else:
	a = sorted(a)
	mid = a[n * m // 2]
	ans = 0
	for i in a:
		ans += abs(i - mid) // d
	print(ans)


import sys, os.path
from collections import *
from copy import *
import math
import os
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
mod = 10 ** 9 + 7
if os.path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')

def check(a):
	p = a[0]
	for i in range(1, n * m):
		b = abs(p - a[i])
		if b % d != 0:
			return 0
	return 1
(n, m, d) = map(int, input().split())
a = []
for i in range(n):
	l = list(map(int, input().split()))
	a.extend(l)
if check(a):
	fix = 0
	sum1 = sys.maxsize
	temp = 0
	for i in range(n * m):
		fix = a[i]
		for j in range(n * m):
			temp += abs(fix - a[j]) // d
		sum1 = min(sum1, temp)
		temp = 0
	print(sum1)
else:
	print(-1)


def Gcd(a, b):
	while a * b != 0:
		if a > b:
			a = int(a) % int(b)
		else:
			b = b % a
	return a + b
(n, m, d) = map(int, input().split())
a = []
for i in range(n):
	a += list(map(int, input().split()))
a = sorted(a)
cnt = 0
mid = a[n * m // 2]
for element in a:
	if mid - element >= 0:
		if (mid - element) % d != 0:
			print(-1)
			exit()
		else:
			cnt += (mid - element) / d
	elif (element - mid) % d != 0:
		print(-1)
		exit()
	else:
		cnt += (element - mid) / d
print(int(cnt))


(n, m, d) = map(int, input().split())
a = []
for i in range(n):
	x = list(map(int, input().split()))
	for j in x:
		a.append(j)
a.sort()
x = a[len(a) // 2]
ans = 0
for i in range(len(a)):
	a[i] = abs(a[i] - x)
	if a[i] % d != 0:
		print(-1)
		exit(0)
	else:
		ans += a[i] // d
print(ans)


import sys
(n, m, d) = map(int, input().split())
a = []
for _ in range(n):
	a += [int(x) for x in input().split()]
a.sort()
for i in range(n * m - 1, -1, -1):
	a[i] -= a[0]
	if a[i] % d != 0:
		print('-1')
		break
else:
	ans = sys.maxsize
	for x in range(0, a[n * m - 1] + 1, d):
		r = 0
		for y in a:
			r += abs(x - y) // d
		ans = min(ans, r)
	print(ans)


import math
(n, m, d) = list(map(int, input().split()))
arr = []
for i in range(0, n):
	arr.append(list(map(int, input().split())))
flat_arr = []
for i in range(0, n):
	for j in range(0, m):
		flat_arr.append(arr[i][j])
flat_arr.sort()
median = []
if len(flat_arr) % 2 == 0:
	index = int((len(flat_arr) - 1) / 2)
	median.append(flat_arr[index])
	median.append(flat_arr[index + 1])
else:
	index = int(len(flat_arr) / 2)
	median.append(flat_arr[index])
min = math.inf
for k in range(0, len(median)):
	check = True
	res = 0
	for i in range(0, len(flat_arr)):
		if abs(flat_arr[i] - median[k]) % d == 0:
			res += int(abs(flat_arr[i] - median[k]) / d)
		else:
			check = False
	if check == True:
		if res < min:
			min = res
if min == math.inf:
	print(-1)
else:
	print(min)


def getInput(n, m):
	data = [0] * (n * m)
	for i in range(0, n):
		row = list(map(int, input().split()))
		data[i * m:(i + 1) * m] = row
	return data
(n, m, d) = map(int, input().split())
data = sorted(getInput(n, m))
median = data[len(data) // 2]
modulus = data[0] % d
res = 0
for n in data:
	if n % d != modulus:
		res = -1
		break
	res += abs((n - median) // d)
print(str(res))


(n, m, d) = map(int, input().split(' '))
a = []
for x in range(0, n):
	l = list(map(int, input().split(' ')))
	a.append(l)
b = []
for x in range(0, n):
	for y in range(0, m):
		b.append(a[x][y])
b.sort()
z = 0
q = 0
c = b[len(b) // 2]
for x in b:
	if abs(x - c) % d != 0:
		print(-1)
		q = 1
		break
	else:
		z = z + abs(x - c) // d
if q == 0:
	print(z)


(n, m, d) = list(map(int, input().split()))
(k, t) = (n * m, [])
for i in range(n):
	t += list(map(int, input().split()))
u = t[0] % d
for v in t:
	if u != v % d:
		t = []
		break
if t:
	t.sort()
	s = t[k // 2]
	print(sum((abs(v - s) for v in t)) // d)
else:
	print(-1)


(n, m, d) = map(int, input().split())
arr = []
for i in range(n):
	temp = [int(x) for x in input().split()]
	for j in temp:
		arr.append(j)
arr = sorted(arr)
ans = 0
val = arr[len(arr) // 2]
for i in arr:
	if abs(i - val) % d != 0:
		ans = -1
		break
	ans += abs(i - val) // d
print(ans)


(n, m, d) = map(int, input().split())
a = []
for i in range(n):
	a.extend(list(map(int, input().split())))
a = sorted(a)
mid = a[len(a) // 2]
ans = 0
for i in a:
	x = abs(mid - i)
	if x % d != 0:
		print(-1)
		exit()
	ans += x // d
print(ans)


(n, m, d) = [int(i) for i in input().split()]
M = []
for i in range(n):
	M += [int(j) for j in input().split()]
mod = M[0] % d
r = 1
for i in M:
	if i % d != mod:
		r = 0
		print(-1)
		break
if r:
	M.sort()
	medium = M[n * m // 2]
	count = 0
	for i in M:
		count += abs(medium - i)
	print(int(count / d))


import sys
import math
import collections

def get_ints():
	return map(int, sys.stdin.readline().strip().split())

def get_list():
	return list(map(int, sys.stdin.readline().strip().split()))

def get_string():
	return sys.stdin.readline().strip()
for t in range(1):
	(n, m, d) = get_ints()
	arr = []
	for i in range(n):
		row = get_list()
		arr += row
	arr.sort()
	size = len(arr)
	uniq = list(set(arr))
	if n * m > 30:
		uniq = arr[size // 2 - 10:size // 2 + 10]
	count = 10 ** 10
	for i in range(len(uniq)):
		ele = uniq[i]
		c = 0
		broken = 0
		for j in range(len(arr)):
			val = arr[j]
			diff = abs(val - ele)
			if diff % d != 0:
				broken += 1
				break
			else:
				c += diff // d
		if broken == 0:
			count = min(count, c)
	if count < 10 ** 10:
		print(count)
	else:
		print(-1)


import math

def main():
	(n, m, d) = map(int, input().split())
	mat = []
	for _ in range(n):
		x = list(map(int, input().split()))
		mat.append(x)
	b = []
	mod = mat[0][0] % d
	for i in range(n):
		for j in range(m):
			if mat[i][j] % d != mod:
				print(-1)
				return
			else:
				b.append(mat[i][j])
	b.sort()
	k = n * m
	if k % 2 != 0:
		val = b[k // 2]
	else:
		val = b[k // 2 - 1]
	ans = 0
	for c in range(len(b)):
		ans += abs(b[c] - val) // d
	print(ans)
main()


(n, m, d) = map(int, input().split())
l = []
for _ in range(n):
	l += list(map(int, input().split()))
l.sort()
mid = n * m // 2
ans = 0
for i in l:
	if abs(i - l[mid]) % d != 0:
		print(-1)
		break
	ans += abs(i - l[mid])
else:
	print(ans // d)


import sys
input = sys.stdin.readline
read = lambda : map(int, input().split())
read_float = lambda : map(float, input().split())

def ceil(x):
	if x != int(x):
		x = int(x) + 1
	return x

def factorial(x, m):
	val = 1
	while x > 0:
		val = val * x % m
		x -= 1
	return val

def fact(x):
	val = 1
	while x > 0:
		val *= x
		x -= 1
	return val

def swaparr(arr, a, b):
	temp = arr[a]
	arr[a] = arr[b]
	arr[b] = temp

def gcd(a, b):
	if b == 0:
		return a
	return gcd(b, a % b)

def lcm(a, b):
	return a * b // math.gcd(a, b)

def nCr(n, k):
	if k > n:
		return 0
	if k > n - k:
		k = n - k
	res = 1
	for i in range(k):
		res = res * (n - i)
		res = res / (i + 1)
	return int(res)

def primefs(n):
	primes = {}
	while n % 2 == 0 and n > 0:
		primes[2] = primes.get(2, 0) + 1
		n = n // 2
	for i in range(3, int(n ** 0.5) + 2, 2):
		while n % i == 0 and n > 0:
			primes[i] = primes.get(i, 0) + 1
			n = n // i
	if n > 2:
		primes[n] = primes.get(n, 0) + 1
	return primes

def power(x, y, p):
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res

def swap(a, b):
	temp = a
	a = b
	b = temp
	return (a, b)

def find(x, link):
	p = x
	while p != link[p]:
		p = link[p]
	while x != p:
		nex = link[x]
		link[x] = p
		x = nex
	return p

def union(x, y, link, size):
	x = find(x, link)
	y = find(y, link)
	if size[x] < size[y]:
		(x, y) = swap(x, y)
	if x != y:
		size[x] += size[y]
		link[y] = x

def sieve(n):
	prime = [True for i in range(n + 1)]
	(prime[0], prime[1]) = (False, False)
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	return prime

def phi(n):
	result = n
	p = 2
	while p * p <= n:
		if n % p == 0:
			while n % p == 0:
				n = n // p
			result = result * (1.0 - 1.0 / float(p))
		p = p + 1
	if n > 1:
		result = result * (1.0 - 1.0 / float(n))
	return int(result)

def is_prime(n):
	if n == 0:
		return False
	if n == 1:
		return True
	for i in range(2, int(n ** (1 / 2)) + 1):
		if not n % i:
			return False
	return True

def next_prime(n, primes):
	while primes[n] != True:
		n += 1
	return n
MAXN = int(100000.0 + 5)

def spf_sieve():
	spf[1] = 1
	for i in range(2, MAXN):
		spf[i] = i
	for i in range(4, MAXN, 2):
		spf[i] = 2
	for i in range(3, ceil(MAXN ** 0.5), 2):
		if spf[i] == i:
			for j in range(i * i, MAXN, i):
				if spf[j] == j:
					spf[j] = i
spf = [0 for i in range(MAXN)]

def factoriazation(x):
	res = []
	for i in range(2, int(x ** 0.5) + 1):
		while x % i == 0:
			res.append(i)
			x //= i
	if x != 1:
		res.append(x)
	return res

def factors(n):
	res = []
	for i in range(1, int(n ** 0.5) + 1):
		if n % i == 0:
			res.append(i)
			res.append(n // i)
	return list(set(res))

def int_array():
	return list(map(int, input().strip().split()))

def float_array():
	return list(map(float, input().strip().split()))

def str_array():
	return input().strip().split()

def binary_search(low, high, w, h, n):
	while low < high:
		mid = low + (high - low) // 2
		if check(mid, w, h, n):
			low = mid + 1
		else:
			high = mid
	return low

def check(l, ps, n, t):
	for i in range(n - l + 1):
		if ps[i + l] - ps[i] <= t:
			return True
	return False
MOD = int(1000000000.0) + 7
CMOD = 998244353
INF = float('inf')
NINF = -float('inf')
from itertools import permutations
import math
import bisect as bis
import random
import sys

def solve():
	(n, m, d) = read()
	penguin_matrix = [list(read()) for x in range(n)]
	new_mat = []
	for i in penguin_matrix:
		for j in i:
			new_mat.append(j)
	new_mat.sort()
	z = new_mat[0] % d
	for x in new_mat:
		if x % d != z:
			print(-1)
			return
	comp = new_mat[n * m // 2]
	summ = 0
	for x in new_mat:
		diff = abs(comp - x)
		summ += diff // d
	print(summ)
for _ in range(1):
	solve()


(n, m, d) = map(int, input().split())
a = []
ans = []
for _ in range(n):
	inn = list(map(int, input().split()))
	a = a + inn
a.sort()
meanSet = [a[len(a) // 2], a[len(a) // 2 - 1]]
for m in meanSet:
	temp = 0
	for v in a:
		ret = abs(m - v) // d
		if abs(m - v) % d != 0:
			ans.append(-1)
			break
		temp += ret
	ans.append(temp)
print(min(ans))


import sys
(n, m, d) = map(int, input().split())
mat = list()
for i in range(0, n):
	x = list(map(int, input().split()))
	mat.append(x)
flat = list()
for i in mat:
	for j in i:
		flat.append(j)
flat.sort()
rem = flat[0] % d
for i in flat:
	remd = i % d
	if remd != rem:
		print('-1')
		sys.exit()
mid = flat[len(flat) // 2]
count = 0
for i in flat:
	diff = abs(i - mid)
	count += diff / d
print(int(count))


def main():
	(n, m, d) = map(int, input().split())
	l = [x for _ in range(n) for x in map(int, input().split())]
	n *= m
	m = min(l)
	for (i, x) in enumerate(l):
		x -= m
		if x % d:
			print(-1)
			return
		l[i] = x
	l.sort()
	m = l[n // 2]
	print(sum((abs(x - m) for x in l)) // d)
main()


(a, b, d) = map(int, input().split())
ans = []
if a == 1 and b == 1:
	print(0)
	exit()
for i in range(a):
	z = list(map(int, input().split()))
	ans.extend(z)
ans.sort()
arr = []
total = 0
for i in range(1, len(ans)):
	arr.append(ans[i] - ans[i - 1])
for i in range(len(arr)):
	if arr[i] % d != 0:
		print(-1)
		exit()
tr = ans[len(ans) // 2]
for i in range(len(ans)):
	total += abs(ans[i] - tr) // d
print(total)


from collections import Counter
import heapq
import math
(n, m, d) = map(int, input().split())
matrix = []
heapq.heapify(matrix)
cnter = Counter()
for i in range(n):
	inp = list(map(int, input().split()))
	for i in range(m):
		heapq.heappush(matrix, inp[i])
		cnter[inp[i]] += 1
times = 0
pivot = heapq.nlargest(math.ceil(n * m / 2), matrix)[-1]
rem = pivot % d
for i in cnter.items():
	el = i
	if el[0] % d == rem:
		times += abs(el[0] - pivot) // d * el[1]
	else:
		print(-1)
		break
else:
	print(times)


(n, m, d) = map(int, input().split())
(k, arr) = (n * m, [])
for i in range(n):
	arr += list(map(int, input().split()))
u = arr[0] % d
for v in arr:
	if u != v % d:
		print(-1)
		exit()
arr.sort()
s = arr[k // 2]
res = [abs(v - s) for v in arr]
print(sum(res) // d)


(n, m, d) = list(map(int, input().split()))
arr = []
for i in range(n):
	arr.append(list(map(int, input().split())))
f = arr[0][0] % d
g = 0
for i in range(n):
	for j in range(m):
		e = arr[i][j] % d
		if e == f:
			pass
		else:
			g = 1
			break
if g == 1:
	print(-1)
else:
	ans = []
	all_val = []
	for i in range(n):
		all_val += arr[i]
	all_val = list(set(all_val))
	for i in all_val:
		cnt = 0
		for j in range(n):
			for k in range(m):
				cnt += abs(i - arr[j][k])
		ans.append(cnt)
	print(min(ans) // d)


(n, m, d) = map(int, input().split())
a = []
s = set()
for i in range(n):
	a += list(map(int, input().split()))
a.sort()
mid = a[len(a) // 2]
ans = 0
for i in a:
	x = abs(i - mid)
	if x % d != 0:
		print(-1)
		exit()
	ans += x // d
print(ans)


(n, m, d) = map(int, input().split())
mat = []
arr = []
for i in range(n):
	temp = list(map(int, input().split()))
	arr.extend(temp)
	mat.append(temp)
ans = -1
tog = 0
for i in range(n):
	for j in range(m):
		temp = mat[i][j] % d
		if ans == -1 or temp == ans:
			ans = temp
		else:
			tog = 1
			break
if tog == 1:
	print(-1)
else:
	arr.sort()
	arr2 = [-1 for x in range(len(arr))]
	for i in range(len(arr)):
		diff = (arr[i] - arr[0]) // d
		arr2[i] = diff
	arr3 = [-1 for x in range(n * m)]
	arr3[0] = arr2[0]
	for i in range(1, len(arr2)):
		arr3[i] = arr3[i - 1] + arr2[i]
	mini = arr3[-1]
	total = arr3[-1]
	for i in range(1, len(arr) - 1):
		var1 = total - arr3[i] - arr2[i] * (len(arr) - (i + 1))
		var2 = arr2[i] * (i + 1) - arr3[i]
		a1 = var1 + var2
		if a1 < mini:
			mini = a1
	print(mini)


(n, m, d) = map(int, input().split())
dd = []
for _ in range(n):
	arr = list(map(int, input().split()))
	dd += arr
dd = sorted(dd)
for i in range(len(dd)):
	if (dd[i] - dd[0]) % d != 0:
		print(-1)
		break
else:
	ll = []
	tt = set(dd)
	tt = list(tt)
	sum = 0
	i = 0
	while i < len(tt):
		for j in range(len(dd)):
			sum += abs(dd[j] - tt[i])
		ll.append(sum)
		sum = 0
		i += 1
	print(min(ll) // d)


(n, m, d) = map(int, input().split())
A = []
for i in range(n):
	A += list(map(int, input().split()))
A = sorted(A)
median = A[m * n // 2]
rem = A[0] % d
sum = 0
for i in range(n * m):
	if A[i] % d != rem:
		print(-1)
		exit()
	else:
		sum += abs(A[i] - median) / d
print(int(sum))


(n, m, d) = map(int, input().split())
a = []
for i in [0] * n:
	a.extend(list(map(int, input().split())))
a = sorted(a)
tmp = a[n * m // 2]
ans = sum((abs(i - tmp) for i in a)) // d
s = set((i % d for i in a))
print([ans, -1][len(s) > 1])


(n, m, d) = map(int, input().split())
arr = []
for _ in range(n):
	arr.extend(map(int, input().split()))
arr.sort()
rem = arr[0] % d

def f(i):
	return sum([abs(arr[i] - x) // d for x in arr])
if all((x % d == rem for x in arr)):
	(l, r) = (0, n * m)
	while abs(r - l) > 3:
		m1 = l + (r - l) // 3
		m2 = r - (r - l) // 3
		f1 = f(m1)
		f2 = f(m2)
		if f1 > f2:
			l = m1
		else:
			r = m2
	print(min([f(i + l) for i in range(r - l)]))
else:
	print(-1)


(n, m, d) = list(map(int, input().split()))
matrix = [list(map(int, input().split())) for i in range(n)]
change = matrix[0][0] % d
flag = 0
count = 0
for i in range(n):
	for j in range(m):
		if change != matrix[i][j] % d:
			flag = 1
			break
if flag:
	print(-1)
else:
	matrixArray = []
	for i in matrix:
		matrixArray += i
	matrixArray.sort()
	median = matrixArray[n * m // 2]
	for i in matrixArray:
		if i < median:
			count += (median - i) // d
		else:
			count += (i - median) // d
	print(count)


log = lambda *x: print(*x)

def cin(*fn, def_fn=str):
	(i, r) = (0, [])
	if fn:
		def_fn = fn[0]
	for c in input().split(' '):
		r += [(fn[i] if len(fn) > i else def_fn)(c)]
		i += 1
	return r

def min_move(m, d, s=0):
	a = sorted([c for l in m for c in l])
	md = a[len(a) // 2]
	r = a[0] % d
	for v in a:
		s += abs(md - v)
		if v % d != r:
			return -1
			break
	return s // d
(n, m, d) = cin(int)
a = []
for i in range(n):
	a += [cin(int)]
log(min_move(a, d))


(n, m, d) = map(int, input().split())
a = []
for i in range(n):
	b = list(map(int, input().split()))
	a.extend(b)
a.sort()
fa = a[0]
f = 0
c = (a[len(a) // 2] - fa) // d
moves = 0
for i in a:
	if (i - fa) % d > 0:
		f = -1
	moves += abs(int((i - fa) / d) - c)
if f == -1:
	print(-1)
else:
	print(moves)


(n, m, d) = map(int, input().split())
mat = []
for i in range(n):
	mat.append(list(map(int, input().split())))
ele = set()
chk = 0
arr = []
for i in range(n):
	for j in range(m):
		ele.add(mat[i][j])
		arr.append(mat[i][j])
if len(ele) == 1:
	print(0)
else:
	arr.sort()
	e = arr[n * m // 2]
	for i in range(n):
		for j in range(m):
			if abs(mat[i][j] - e) % d != 0:
				chk += 1
	if chk != 0:
		print(-1)
	else:
		moves = 0
		for i in range(n):
			for j in range(m):
				if e > mat[i][j]:
					moves += abs(mat[i][j] - e) // d
				if e < mat[i][j]:
					moves += abs(mat[i][j] - e) // d
		print(moves)


import sys, os, io

def rs():
	return sys.stdin.readline().rstrip()

def ri():
	return int(sys.stdin.readline())

def ria():
	return list(map(int, sys.stdin.readline().split()))

def ws(s):
	sys.stdout.write(s + '\n')

def wi(n):
	sys.stdout.write(str(n) + '\n')

def wia(a):
	sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
import math, datetime, functools, itertools, operator, bisect, fractions, statistics
from collections import deque, defaultdict, OrderedDict, Counter
from fractions import Fraction
from decimal import Decimal
from sys import stdout
from heapq import heappush, heappop, heapify, _heapify_max, _heappop_max, nsmallest, nlargest
INF = 99999999999999999999999999999999

def main():
	mod = 1000000007
	starttime = datetime.datetime.now()
	if os.path.exists('input.txt'):
		sys.stdin = open('input.txt', 'r')
		sys.stdout = open('output.txt', 'w')
	tc = 1
	for _ in range(tc):
		(n, m, d) = ria()
		a = []
		z = []
		for i in range(n):
			for j in ria():
				z.append(j % d)
				a.append(j)
		if len(set(z)) == 1:
			a = sorted(a)
			ans = 0
			for i in a:
				ans += abs(i - a[n * m // 2])
			ans = ans // d
			wi(ans)
		else:
			wi(-1)
	endtime = datetime.datetime.now()
	time = (endtime - starttime).total_seconds() * 1000
	if os.path.exists('input.txt'):
		print('Time:', time, 'ms')

class FastReader(io.IOBase):
	newlines = 0

	def __init__(self, fd, chunk_size=1024 * 8):
		self._fd = fd
		self._chunk_size = chunk_size
		self.buffer = io.BytesIO()

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self, size=-1):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size if size == -1 else size))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

class FastWriter(io.IOBase):

	def __init__(self, fd):
		self._fd = fd
		self.buffer = io.BytesIO()
		self.write = self.buffer.write

	def flush(self):
		os.write(self._fd, self.buffer.getvalue())
		(self.buffer.truncate(0), self.buffer.seek(0))

class FastStdin(io.IOBase):

	def __init__(self, fd=0):
		self.buffer = FastReader(fd)
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

class FastStdout(io.IOBase):

	def __init__(self, fd=1):
		self.buffer = FastWriter(fd)
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.flush = self.buffer.flush
sys.stdin = FastStdin()
sys.stdout = FastStdout()
main()


import sys
from functools import lru_cache, cmp_to_key
from heapq import merge, heapify, heappop, heappush
from collections import defaultdict as dd, deque, Counter as C
from itertools import combinations as comb, permutations as perm
from bisect import bisect_left as bl, bisect_right as br, bisect
from time import perf_counter
from fractions import Fraction
import copy
import time
starttime = time.time()
mod = int(pow(10, 9) + 7)
mod2 = 998244353

def data():
	return sys.stdin.readline().strip()

def out(*var, end='\n'):
	sys.stdout.write(' '.join(map(str, var)) + end)

def L():
	return list(sp())

def sl():
	return list(ssp())

def sp():
	return map(int, data().split())

def ssp():
	return map(str, data().split())

def l1d(n, val=0):
	return [val for i in range(n)]

def l2d(n, m, val=0):
	return [l1d(n, val) for j in range(m)]
try:
	sys.stdin = open('input.txt', 'r')
except:
	pass
(n, m, d) = L()
A = [L() for i in range(n)]
s = set()
x = []
for i in range(n):
	for j in range(m):
		if len(s) == 0:
			s.add(A[i][j] % d)
		elif A[i][j] % d not in s:
			print(-1)
			exit()
	x += A[i]
x.sort()
z = len(x)
if z % 2:
	a = x[z // 2]
	z = sum((abs(ele - a) // d for ele in x))
	print(z)
else:
	a = x[z // 2]
	z1 = sum((abs(ele - a) // d for ele in x))
	a = x[min(z // 2 + 1, z - 1)]
	z2 = sum((abs(ele - a) // d for ele in x))
	print(min(z1, z2))
endtime = time.time()


import sys
import time
import os
from math import sqrt, log, log2, ceil, log10, gcd, floor, pow, sin, cos, tan, pi, inf, factorial
from copy import copy, deepcopy
from sys import exit, stdin, stdout
from collections import Counter, defaultdict, deque
from itertools import permutations
import heapq
from bisect import bisect_left as bl
from bisect import bisect_right as br
from bisect import bisect
mod = 1000000007
iinp = lambda : int(sys.stdin.readline())
inp = lambda : sys.stdin.readline().strip()
strl = lambda : list(inp().strip().split(' '))
intl = lambda : list(map(int, inp().split(' ')))
mint = lambda : map(int, inp().split())
flol = lambda : list(map(float, inp().split(' ')))
flush = lambda : stdout.flush()

def permute(nums):

	def fun(arr, nums, cur, v):
		if len(cur) == len(nums):
			arr.append(cur.copy())
		i = 0
		while i < len(nums):
			if v[i]:
				i += 1
				continue
			else:
				cur.append(nums[i])
				v[i] = 1
				fun(arr, nums, cur, v)
				cur.pop()
				v[i] = 0
				i += 1
		return arr
	res = []
	nums.sort()
	v = [0] * len(nums)
	return fun(res, nums, [], v)

def subsets(res, index, arr, cur):
	res.append(cur.copy())
	for i in range(index, len(arr)):
		cur.append(arr[i])
		subsets(res, i + 1, arr, cur)
		cur.pop()
	return res

def sieve(N):
	root = int(sqrt(N))
	primes = [1] * (N + 1)
	(primes[0], primes[1]) = (0, 0)
	for i in range(2, root + 1):
		if primes[i]:
			for j in range(i * i, N + 1, i):
				primes[j] = 0
	return primes

def bs(arr, l, r, x):
	if x < arr[0] or x > arr[len(arr) - 1]:
		return -1
	while l <= r:
		mid = l + (r - l) // 2
		if arr[mid] == x:
			return mid
		elif arr[mid] < x:
			l = mid + 1
		else:
			r = mid - 1
	return -1

def isPrime(n):
	if n <= 1:
		return False
	if n <= 3:
		return True
	if n % 2 == 0 or n % 3 == 0:
		return False
	p = int(sqrt(n))
	for i in range(5, p + 1, 6):
		if n % i == 0 or n % (i + 2) == 0:
			return False
	return True

def solve():
	(n, m, d) = mint()
	arr = []
	for i in range(n):
		arr.extend(intl())
	arr.sort()
	flag = 0
	ans = 0
	median = n * m // 2
	for i in range(n * m):
		if abs(arr[median] - arr[i]) % d != 0:
			flag = 1
			break
		else:
			ans += abs(arr[median] - arr[i]) // d
	print(ans) if not flag else print(-1)
start_time = time.time()
solve()


(n, m, d) = map(int, input().split())
mat = []
for i in range(n):
	arr = [int(i) for i in input().split()]
	mat.append(arr)
arr = []
for i in range(n):
	for j in range(m):
		arr.append(mat[i][j])
arr.sort()
if True:
	med = arr[len(arr) // 2]
	ans = 0
	boo = True
	for i in range(n * m):
		if abs(arr[i] - med) % d != 0:
			print(-1)
			boo = False
			break
		else:
			ans = ans + abs(arr[i] - med) // d
	if boo:
		print(ans)


import sys

def answer(n, m, d, a):
	a.sort()
	med = a[n * m // 2]
	num_moves = 0
	for i in range(n * m):
		diff = abs(a[i] - med)
		if diff % d == 0:
			num_moves += diff // d
		else:
			return -1
	return num_moves

def main():
	(n, m, d) = map(int, sys.stdin.readline().split())
	a = []
	for i in range(n):
		a.extend(list(map(int, sys.stdin.readline().split())))
	print(answer(n, m, d, a))
	return
main()


(n, m, d) = map(int, input().split())
matrix = []
for i in range(n):
	matrix.append(list(map(int, input().split())))
v = []
for i in range(n):
	v.extend(matrix[i])
v.sort()
remender = set()
for i in v:
	remender.add(i % d)
if len(remender) > 1:
	print('-1')
else:
	ans = 0
	middle_element = v[n * m // 2]
	for i in v:
		ans += abs(i - middle_element)
	print(ans // d)


(n, m, d) = map(int, input().split())
l = list()
for _ in range(n):
	l += list(map(int, input().split()))
mcost = 9999999999
me = min(l)
for please in range(max(l)):
	cost = 0
	for (i, e) in enumerate(l):
		if (e - me) % d != 0:
			print(-1)
			exit()
		cost += abs(e // d - please)
	if cost < mcost:
		mcost = cost
print(0 if n * m == 1 else mcost)


from itertools import chain, accumulate
(n, m, d) = [int(i) for i in input().split()]
ls = [0]
for i in range(n):
	l = [int(i) for i in input().split()]
	ls = list(chain(ls, l))
for i in ls[1:]:
	if i % d != ls[1] % d:
		print(-1)
		exit()
ls.sort()
lsum = list(accumulate(ls))
ssum = lsum[len(ls) - 1]
step = []
for i in range(1, len(ls)):
	x = (ssum - lsum[i] - ls[i] * (len(ls) - 1 - i) - (lsum[i - 1] - ls[i] * (i - 1))) // d
	step.append(x)
print(min(step))


(n, m, d) = map(int, input().split())
l = []
for i in range(n):
	l = l + list(map(int, input().split()))
l.sort()
mi = len(l) // 2
mid = l[mi]
count = 0
e = 0
for i in range(mi):
	k = abs(mid - l[i])
	if k % d == 0:
		r = k // d
		count = count + r
	else:
		e = 1
		break
if e == 1:
	print('-1')
else:
	for i in range(mi + 1, len(l)):
		k = abs(mid - l[i])
		if k % d == 0:
			r = k // d
			count = count + r
		else:
			e = 1
			break
	if e == 1:
		print('-1')
	else:
		print(count)


(n, m, d) = [int(x) for x in input().split(' ')]
total = n * m
total_matrix = []
for i in range(n):
	total_matrix += [int(x) for x in input().split(' ')]
total_matrix = sorted(total_matrix)
middle = total // 2
not_possible = False
count = 0
for el in total_matrix:
	if abs(total_matrix[middle] - el) % d != 0:
		not_possible = True
		break
	else:
		count += abs(total_matrix[middle] - el) // d
if not_possible:
	print(-1)
else:
	print(count)


from statistics import median
a = []
(n, m, dd) = map(int, input().split())
for i in range(n):
	j = list(map(int, input().split()))
	a = a + j
a.sort()
mean = a[n * m // 2]
ans = 0
for i in range(n * m):
	c = abs(mean - a[i]) // dd
	d = abs(mean - a[i]) % dd
	if d == 0:
		ans += c
	else:
		print(-1)
		exit()
print(ans)


(n, m, d) = map(int, input().split())
arr = (tuple(map(int, input().split())) for _ in range(n))
e = [x for r in arr for x in r]
e.sort()
for i in range(n * m - 1):
	if (e[i + 1] - e[i]) % d:
		print(-1)
		exit()
mid = n * m // 2
ans = 0
for i in e:
	ans += abs(i - e[mid]) // d
print(ans)


import math as mt
import sys, string, bisect
input = sys.stdin.readline
import random
from collections import deque, defaultdict
L = lambda : list(map(int, input().split()))
Ls = lambda : list(input().split())
M = lambda : map(int, input().split())
I = lambda : int(input())
d = defaultdict(int)
(n, m, d) = M()
l = []
for i in range(n):
	x = L()
	for j in x:
		l.append(j)
l.sort()
w = l[0] % d
for i in range(m * n):
	if l[i] % d != w:
		print(-1)
		exit()
key = l[m * n // 2]
key2 = l[m * n // 2 - 1]
s = 0
s2 = 0
for i in range(n * m):
	s += abs(l[i] - key)
	s2 += abs(l[i] - key2)
print(min(s // d, s2 // d))


matrix = []
(m, n, d) = map(int, input().split())
for i in range(m):
	row = list(map(int, input().split()))
	for i in range(n):
		matrix.append(row[i])
matrix.sort()
f = 0
z = matrix[0] % d
for i in range(1, m * n):
	if z != matrix[i] % d:
		print(-1)
		f = 1
		break
steps = 0
median = matrix[n * m // 2]
for i in range(m * n):
	steps += abs(median - matrix[i]) // d
if not f:
	print(steps)


a = []
(n, m, d) = map(int, input().split())
for i in range(n):
	l = []
	l = list(map(int, input().split()))
	a.append(l)
c = []
for i in range(n):
	for j in range(m):
		c.append(a[i][j])
c.sort()
flag = 0
if len(c) == 1:
	print(0)
elif len(c) == 2 and d != c[1] - c[0]:
	print(-1)
else:
	val = c[0] % d
	k = m * n
	median = c[k // 2]
	for i in range(1, k):
		if c[i] % d != val:
			print(-1)
			flag = 1
			break
	ans = 0
	if flag == 0:
		for i in range(k):
			ans += abs(c[i] - median) // d
		print(ans)


def solve(l, n, m, d):
	mv = 0
	mid = l[n * m // 2]
	for i in range(n * m):
		if abs(l[i] - mid) % d != 0:
			print(-1)
			return
		else:
			mv += abs(l[i] - mid) // d
	print(mv)
	return
(n, m, d) = map(int, input().split())
li = [[int(x) for x in input().split()] for i in range(n)]
sm = 0
(mn, mx) = (1000000000000, -9)
l = []
for i in range(n):
	for j in range(m):
		l.append(li[i][j])
l.sort()
solve(l, n, m, d)


(n, m, d) = map(int, input().split())
l = []
for _ in range(n):
	h = list(map(int, input().split()))
	l.extend(h)
k = l[0] % d
c = 0
for i in range(n * m):
	if l[i] % d != k:
		print(-1)
		c = -1
		break
if c == 0:
	l.sort()
	median = l[(n * m - 1) // 2]
	for i in l:
		c += abs(i - median) // d
	print(c)


(n, m, d) = map(int, input().split())
arr = []
for _ in range(n):
	arr.extend(list(map(int, input().split())))
arr.sort()
size = n * m
median = arr[size // 2]
arr = [abs(i - median) for i in arr]
s = sum(arr)
if s % d == 0:
	print(s // d)
else:
	print('-1')


(n, m, d) = (int(x) for x in input().split())
s = set()
l = []
for i in range(n):
	tmp = [int(x) for x in input().split()]
	s |= {x % d for x in tmp}
	l += [x // d for x in tmp]
if len(s) != 1:
	print(-1)
	return
l.sort()
mean = l[n * m // 2]
ans = 0
for x in l:
	ans += abs(x - mean)
if n * m // 2 > 0:
	mean = l[n * m // 2 - 1]
	ans2 = 0
	for x in l:
		ans2 += abs(x - mean)
	ans = min(ans, ans2)
print(ans)


(m, n, d) = map(int, input().split())
matrix = []
for i in range(m):
	matrix += list(map(int, input().split()))
remainder = set()
matrix.sort()
result = 0
median = matrix[len(matrix) // 2]
for i in matrix:
	remainder.add(i % d)
	result += abs(i - median) // d
if len(remainder) > 1:
	print(-1)
else:
	print(result)


import sys
(a, b, c) = map(int, input().split())
l = [0] * (a * b)
d = [[0 for j in range(b)] for i in range(a)]
for i in range(a):
	d[i] = list(map(int, input().split()))
t = 0
for i in range(a):
	for j in range(b):
		l[t] = d[i][j]
		t += 1
l.sort()
for i in range(a * b - 1):
	if l[i] % c != l[i + 1] % c:
		print(-1)
		sys.exit()
c3 = l[a * b // 2]
c2 = l[a * b // 2 - 1]
ans = 0
ans2 = 0
for i in range(a * b):
	ans += abs(l[i] - c3)
	ans2 += abs(l[i] - c2)
cw = min(ans, ans2)
print(cw // c)


from sys import stdin, stdout
import math
import bisect
input = stdin.readline

def print(x='', y='', end='\n'):
	if y == '':
		stdout.write(str(x) + end)
	else:
		stdout.write(str(x) + ' ' + str(y) + end)

def solve():
	(n, m, d) = map(int, input().split())
	l = []
	for i in range(n):
		l.extend(list(map(int, input().split())))
	l.sort()
	c = l[0] % d
	for i in range(n * m):
		if l[i] % d != c:
			print(-1)
			return
	ans = 0
	med = l[n * m // 2]
	for i in range(m * n):
		ans += abs(l[i] - med) // d
	print(ans)
tt = 1
for __ in range(tt):
	solve()


import os
import sys
from math import *
from collections import *
from fractions import *
from bisect import *
from heapq import *
from io import BytesIO, IOBase

def vsInput():
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def value():
	return tuple(map(int, input().split()))

def array():
	return [int(i) for i in input().split()]

def Int():
	return int(input())

def Str():
	return input()

def arrayS():
	return [i for i in input().split()]

def steps(x):
	x = a[x]
	s = 0
	for i in a:
		if abs(i - x) % d:
			return -1
		s += abs(i - x) // d
	return s
(n, m, d) = value()
a = []
for i in range(n):
	a.extend(array())
a.sort()
low = 0
high = n * m - 1
while low <= high:
	mid1 = low + (high - low) // 3
	mid2 = high - (high - low) // 3
	if steps(mid1) < steps(mid2):
		high = mid2 - 1
		ans = mid1
	else:
		low = mid1 + 1
		ans = mid2
print(steps(ans))


from os import path
import sys, time, collections as c, math as m, pprint as p
(maxx, localsys, mod) = (float('inf'), 0, int(1000000000.0 + 7))
if path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
input = sys.stdin.readline
(n, m, k) = map(int, input().split())
arr = []
for _ in range(n):
	arr.extend(map(int, input().split()))
arr.sort()
(med, x) = (arr[n * m // 2], 0)
for i in range(n * m):
	x += abs(med - arr[i])
print(-1 if x % k else int(x // k))


import math
(n, m, d) = map(int, input().split())
mat = []
for i in range(n):
	row = list(map(int, input().split()))
	mat += row
mat = sorted(mat)
ans = 0
check = mat[0] % d
for i in range(1, n * m):
	if mat[i] % d != check:
		ans = -1
if ans != -1:
	lim = n * m // 2
	for i in range(lim):
		ans += mat[lim] - mat[i]
	for i in range(lim, n * m):
		ans += mat[i] - mat[lim]
	ans = ans // d
print(ans)


(n, m, d) = map(int, input().split())
b = [[int(i) for i in input().split()] for j in range(n)]
a = []
for i in range(n):
	for j in range(m):
		a.append(b[i][j])
a.sort()
f = 1
l = n * m
for i in range(l - 1):
	if a[i] % d != a[i + 1] % d:
		f = 0
		break
if f == 0:
	print(-1)
else:
	k = l // 2
	s = 0
	for i in range(l):
		s += abs(a[k] - a[i]) // d
	print(s)


(n, m, d) = map(int, input().split())
l = []
for i in range(n):
	temp = [int(x) for x in input().split()]
	l.extend(temp)
s = []
s = set(s)
for i in l:
	s.add(i % d)
if len(s) != 1:
	print(-1)
else:
	ans = 10 ** 9
	for i in l:
		temp = 0
		for j in l:
			temp += abs(i - j) // d
		if temp < ans:
			ans = temp
	print(ans)


(n, m, d) = map(int, input().split())
ans = True
hehe = -1
mat = []
for i in range(n):
	row = list(map(int, input().split()))
	for k in row:
		mat.append(k)
	for j in range(m):
		if i == 0 and j == 0:
			hehe = row[j] % d
			continue
		if row[j] % d != hehe:
			ans = False
if not ans:
	print(-1)
else:
	maxxx = -1
	mat.sort()
	l = len(mat) // 2
	mid = mat[l]
	summ = 0
	for h in mat:
		summ += abs(mid - h) // d
	print(summ)


(n, m, d) = map(int, input().split())
arr = []
brr = set()
for i in range(n):
	temp = list(map(int, input().split()))
	arr.extend(temp)
for i in range(n * m):
	t = arr[i]
	brr.add(t % d)
if len(brr) > 1:
	print(-1)
else:
	arr.sort()
	median = arr[n * m // 2]
	ans = 0
	for i in range(n * m):
		ans += abs(median - arr[i]) // d
	print(ans)


from sys import stdout, stdin, setrecursionlimit
from io import BytesIO, IOBase
from collections import *
from itertools import *
from random import *
from bisect import *
from string import *
from queue import *
from heapq import *
from math import *
from re import *
from os import *

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = read(self._fd, max(fstat(self._fd).st_size, 8192))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = read(self._fd, max(fstat(self._fd).st_size, 8192))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(stdin, stdout) = (IOWrapper(stdin), IOWrapper(stdout))

def input():
	return stdin.readline().strip()

def fast():
	return stdin.readline().strip()

def zzz():
	return [int(i) for i in fast().split()]
(z, zz) = (fast, lambda : map(int, z().split()))
(szz, graph, mod, szzz) = (lambda : sorted(zz()), {}, 10 ** 9 + 7, lambda : sorted(zzz()))

def lcd(xnum1, xnum2):
	return xnum1 * xnum2 // gcd(xnum1, xnum2)

def output(answer, end='\n'):
	stdout.write(str(answer) + end)
dx = [-1, 1, 0, 0, 1, -1, 1, -1]
dy = [0, 0, 1, -1, 1, -1, -1, 1]
(n, m, k) = zzz()
matrix = []
for _ in range(n):
	arr = zzz()
	matrix += arr
ans = True
matrix = sorted(matrix)
rem = set()
for i in matrix:
	rem.add(i % k)
if len(rem) > 1:
	print(-1)
else:
	mid = m * n // 2
	ans = 0
	for i in matrix:
		ans += abs(i - matrix[mid]) // k
	print(ans)


import sys
input = sys.stdin.readline

def gint():
	return int(input())

def gint_arr():
	return list(map(int, input().split()))

def gfloat():
	return float(input())

def gfloat_arr():
	return list(map(float, input().split()))

def pair_int():
	return map(int, input().split())
INF = 1 << 31
dx = [-1, 0, 1, 0]
dy = [0, 1, 0, -1]
(n, m, d) = gint_arr()
a = []
for i in range(n):
	a.extend(gint_arr())
a.sort()
target = a[n * m // 2]
mod = -1
res = 0
for v in a:
	if ~mod and abs(v - target) % d != mod:
		print('-1')
		exit()
	else:
		res += abs(v - target) / d
		mod = abs(v - target) % d
print(int(res))


(n, m, d) = map(int, input().split())
l = []
for i in range(n):
	l.append(list(map(int, input().split())))
min1 = 10000000000
dic = {}
for i in range(n):
	for j in range(m):
		if dic.get(l[i][j]) == None:
			dic[l[i][j]] = 1
		else:
			dic[l[i][j]] += 1
		if l[i][j] < min1:
			min1 = l[i][j]
sum = 0
l = sorted(dic.keys())
for i in l:
	k = 0
	if (i - min1) % d == 0:
		k = 1
		sum += (i - min1) * dic[i] // d
	if k == 0:
		break
if k == 0:
	print(-1)
else:
	s1 = [dic[l[0]]]
	s2 = [dic[l[-1]]]
	min2 = sum
	ind = 1
	min1 = min(l)
	max1 = max(l)
	for i in range(1, len(l)):
		s1.append(s1[i - 1] + dic[l[i]])
		s2.append(s2[i - 1] + dic[l[len(l) - 1 - i]])
	for i in range(min1 + d, max1 + 1, d):
		if i == l[ind]:
			sum = sum + s1[ind - 1] - s2[len(l) - 1 - ind]
			ind += 1
		elif l[ind] > i:
			sum = sum + s1[ind - 1] - s2[len(l) - 1 - ind]
		if sum < min2:
			min2 = sum
	print(min2)


(n, m, d) = [int(x) for x in input().split()]
a = []
for _ in range(n):
	a.extend([int(x) for x in input().split()])
a.sort()
mid = 0
flag = False
if len(a) == 1:
	print(0)
	flag = True
elif len(a) % 2 != 0:
	mid = a[len(a) // 2]
else:
	mid = a[(len(a) + 1) // 2]
c = 0
if not flag:
	for x in a:
		if abs(x - mid) % d != 0:
			print(-1)
			break
		else:
			c += abs(x - mid) // d
	else:
		print(c)


(n, m, d) = map(int, input().split())
mat = []
for _ in range(n):
	mat.extend([*map(int, input().split())])
mat.sort()
ch = [i % d for i in mat]
if len(set(ch)) > 1:
	print(-1)
else:
	print(sum((abs(i - mat[n * m // 2]) for i in mat)) // d)


(n, m, d) = (int(i) for i in input().split())
l = []
for i in range(n):
	l += [int(i) for i in input().split()]
l = sorted(l)
mod = l[0] % d
for i in range(n * m):
	if l[i] % d != mod:
		mod = -1
		break
if mod == -1:
	print(-1)
else:
	k = l[n * m // 2]
	moves = 0
	for i in range(n * m):
		moves += abs(l[i] - k) // d
	print(moves)


(n, m, d) = list(map(int, input().split()))
ll = []
for i in range(n):
	temp = [int(x) for x in input().split()]
	ll.append(temp)
l = []
for i in range(n):
	for j in range(len(ll[i])):
		l.append(ll[i][j])
flag = 0
l = sorted(l)
for i in range(len(l) - 1):
	if abs(l[i] - l[i + 1]) % d != 0:
		flag = 1
		break
median = l[len(l) // 2]
moves = 0
for i in range(len(l)):
	moves += abs(l[i] - median) // d
if flag == 1:
	print(-1)
else:
	print(moves)


(n, m, d) = map(int, input().split())
a = []
check = 1
limit = 10001
minX = 1000000000
mark = [0 for _ in range(limit)]
ans = []
for _ in range(n):
	inn = list(map(int, input().split()))
	a = a + inn
mem = {a[0]}
total = a[0]
mark[a[0]] = 1
for i in range(1, len(a)):
	mark[a[i]] += 1
	mem.add(a[i])
	if abs(a[0] - a[i]) % d != 0:
		check = 0
		break
	else:
		total += a[i]
meanSet = []
if check:
	mean = round(total / len(a))
	if mark[mean] > 0:
		temp = 0
		for v in mem:
			mul = mark[v]
			temp += abs(mean - v) * mul // d
		minX = temp
	(l, r) = (mean, mean)
	while 1:
		l -= 1
		if l > 0:
			if mark[l] > 0:
				temp = 0
				for v in mem:
					mul = mark[v]
					temp += abs(l - v) * mul // d
					if temp > minX:
						break
				if temp > minX:
					break
				else:
					minX = temp
		else:
			break
	while 1:
		r += 1
		if r < limit:
			if mark[r] > 0:
				temp = 0
				for v in mem:
					mul = mark[v]
					temp += abs(r - v) * mul // d
					if temp > minX:
						break
				if temp > minX:
					break
				else:
					minX = temp
		else:
			break
print(minX if check else -1)


(n, m, d) = map(int, input().split())
a = []
for _ in range(n):
	a.extend([int(i) for i in input().split()])
n = len(a)
a.sort()
p = [i for i in a]
for i in range(1, n):
	p[i] += p[i - 1]
moves = float('inf')
for i in range(n):
	x = p[n - 1] - p[i] - (n - i - 1) * a[i]
	if x % d != 0:
		continue
	x //= d
	y = i * a[i] - (p[i - 1] if i - 1 >= 0 else 0)
	if y % d != 0:
		continue
	y //= d
	moves = min(moves, x + y)
if moves == float('inf'):
	moves = -1
print(moves)


(n, m, d) = map(int, input().split())
l = []
s = set()
for _ in range(n):
	for i in list(map(int, input().split())):
		l.append(i)
		s.add(i % d)
if len(s) > 1:
	print(-1)
	exit()
l.sort()
a = l[n * m // 2]
ans = 0
for i in l:
	ans += abs(i - a) // d
print(ans)


import sys
input = lambda : sys.stdin.readline().strip('\r\n')
(n, m, d) = map(int, input().split())
mat = []
for i in range(n):
	mat += map(int, input().split())
mat.sort()
for i in mat:
	if (i - mat[0]) % d:
		print(-1)
		exit()
median = mat[len(mat) // 2]
ls = map(lambda x: abs(x - median), mat)
print(sum(ls) // d)


(n, m, d) = input().split()
n = int(n)
m = int(m)
d = int(d)
l = []
for i in range(n):
	l1 = [int(x) for x in input().split()]
	l += l1
l.sort()
mid = l[int(n * m / 2)]
for i in range(len(l)):
	l[i] = abs(l[i] - mid)
s = sum(l)
if s % d == 0:
	print(int(s / d))
else:
	print(-1)


def solve(n, m, matrix, d, median):
	ans = 0
	for r in range(n):
		for c in range(m):
			elm = matrix[r][c]
			if (elm - median) % d != 0:
				return -1
			ans += abs((elm - median) // d)
	return ans

def main():
	(n, m, d) = map(int, input().split())
	matrix = []
	elms = []
	for _ in range(n):
		row = [int(c) for c in input().split()]
		elms += row
		matrix.append(row)
	elms.sort()
	median = elms[n * m // 2]
	ans = solve(n, m, matrix, d, median)
	print(ans)
main()


(n, m, d) = map(int, input().split())
arr = []
mat = []
for i in range(n):
	meri = list(map(int, input().split()))
	mat.append(meri)
	for j in meri:
		arr.append(j)
p = 1
l = len(arr)
for i in range(l):
	if abs(arr[i] - arr[0]) % d != 0:
		p = 0
		print(-1)
		break
if p:
	arr.sort()
	s = 0
	e = l - 1
	ans = 10 ** 17
	while s <= e:
		m1 = (e - s) // 3 + s
		m2 = 2 * ((e - s) // 3) + s
		(t1, t2) = (0, 0)
		for i in range(n):
			for j in range(m):
				t1 += abs(mat[i][j] - arr[m1]) // d
				t2 += abs(mat[i][j] - arr[m2]) // d
		ans = min(ans, t1, t2)
		if t1 >= t2:
			s = m1 + 1
		else:
			e = m2 - 1
	print(ans)


(n, m, d) = [int(x) for x in input().split()]
a = []
for i in range(n):
	a += [int(x) for x in input().split()]
a.sort()
l = n * m
mid = l // 2
ans = f = 0
for i in range(0, mid):
	x = a[mid] - a[i]
	if x % d != 0:
		f = 1
		break
	else:
		ans += x / d
if f == 0:
	for i in range(mid + 1, l):
		x = a[i] - a[mid]
		if x % d != 0:
			f = 1
			break
		else:
			ans += x / d
if f == 1:
	print(-1)
else:
	print(int(ans))