#include <bits/stdc++.h>
using namespace std;
long long binDec(string n) {
  string num = n;
  long long dec_value = 0;
  long long base = 1;
  long long len = num.length();
  for (long long i = len - 1; i >= 0; i--) {
    if (num[i] == '1') dec_value += base;
    base = (base * 2);
  }
  return dec_value;
}
long long sub(string s, string q) {
  long long j = 0;
  long long a = s.length();
  long long b = q.length();
  for (long long i = 0; i < a && j < b; ++i) {
    if (q[j] == s[i]) j++;
  }
  if (j == b)
    return 1;
  else
    return 0;
}
bool sort_desc(const pair<long long, long long> &a,
               const pair<long long, long long> &b) {
  return a.second > b.second;
}
char mmv(char c, long long a) {
  string arr[3] = {"qwertyuiop", "asdfghjkl;", "zxcvbnm,./"};
  for (long long i = 0; i < 3; ++i) {
    for (long long j = 0; j < 10; ++j) {
      if (c == arr[i][j]) {
        if (a)
          return arr[i][j - 1];
        else
          return arr[i][j + 1];
      }
    }
  }
}
unsigned Ram() {
  long long n, m, count = 0, i, c = 0, d = 0;
  cin >> n >> m >> d;
  long long arr[n][m], a[n * m];
  for (long long i = 0; i < n; ++i)
    for (long long j = 0; j < m; ++j) {
      cin >> arr[i][j];
    }
  long long l;
  l = arr[0][0] % d;
  if (c) {
    cout << -1;
    return 0;
  }
  long long k = 0;
  ;
  for (long long i = 0; i < n; ++i)
    for (long long j = 0; j < m; ++j) a[k] = arr[i][j], k++;
  sort(a, a + n * m);
  for (long long i = 0; i < k; ++i)
    if (a[i] % d != l) {
      cout << -1;
      return 0;
    }
  c = a[(n * m) / 2];
  for (long long i = 0; i < n * m; ++i) count += abs(a[i] - c) / d;
  cout << count;
}
signed main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  long long t;
  t = 1;
  while (t--) {
    Ram();
    cout << '\n';
  }
  return 0;
}
