#include <bits/stdc++.h>
using namespace std;
int abs(int a) { return a < 0 ? -a : a; }
int toTop(double tar, int d, int res) {
  while (res < tar) res += d;
  return res;
}
int toBottom(double tar, int d, int res) {
  while (res + d <= tar) res += d;
  return res;
}
int main() {
  int n, m, d;
  cin >> n >> m >> d;
  int mat[n][m];
  bool ok = true;
  int mod;
  int sum = 0;
  int may = 0;
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      cin >> mat[i][j];
      may = max(mat[i][j], may);
      sum += mat[i][j];
      if (!i && !j) {
        mod = mat[i][j] % d;
      } else
        ok &= (mat[i][j] % d) == mod;
    }
  }
  if (ok) {
    int res = 0x7fffffff;
    int act = 0;
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) mat[i][j] -= mod;
    }
    for (int i = 0; i <= may; i += d) {
      act = 0;
      for (int a = 0; a < n; a++) {
        for (int j = 0; j < m; j++) {
          act += abs(mat[a][j] - i) / d;
        }
      }
      res = min(act, res);
    }
    cout << res << endl;
  } else
    cout << -1 << endl;
  return 0;
}
