#include <bits/stdc++.h>
using namespace std;
int main() {
  int n, m, d;
  scanf("%d %d %d", &n, &m, &d);
  int i, j, k = 0;
  int a[n][m], arr[n * m];
  for (i = 0; i < n; i++) {
    for (j = 0; j < m; j++) {
      scanf("%d", &a[i][j]);
      arr[k] = a[i][j];
      k++;
    }
  }
  sort(arr, arr + k);
  int mid = k / 2, moves = 0;
  int temp = arr[0];
  for (i = 1; i < k; i++) {
    if (abs(temp - arr[i]) % d != 0) break;
  }
  if (i == k) {
    for (i = 0; i < k; i++) {
      moves += abs(arr[mid] - arr[i]) / d;
    }
    cout << moves;
  } else {
    cout << "-1";
  }
  return 0;
}
