#include <bits/stdc++.h>
using namespace std;
int main() {
  int n, m, d;
  cin >> n >> m >> d;
  int mat[n][m];
  int p[10001];
  int a[10001];
  int arr[n * m];
  for (int i = 0; i < 10001; i++) {
    p[i] = 0;
  }
  int z = 0;
  int u = 0;
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      cin >> mat[i][j];
      p[mat[i][j]]++;
      arr[u] = mat[i][j];
      u++;
    }
  }
  for (int i = 0; i < 10001; i++) {
    if (p[i] > 0) {
      a[z] = i;
      z++;
    }
  }
  sort(a, a + z);
  int t = a[1] - a[0];
  int flag = 0;
  for (int i = 0; i < z - 1; i++) {
    if ((a[i + 1] - a[i]) % d != 0) {
      flag = 1;
      break;
    }
  }
  int anss = 0;
  sort(arr, arr + u);
  if (flag == 0) {
    int h = u / 2;
    for (int i = 0; i < h; i++) {
      anss = anss + (arr[h] - arr[i]) + (arr[u - i - 1] - arr[h]);
    }
    cout << anss / d << endl;
  } else {
    cout << "-1" << endl;
  }
  return 0;
}
