#include <bits/stdc++.h>
using namespace std;
int main() {
  int a, b, c, k;
  vector<int> d;
  cin >> a >> b >> c;
  int modul = 0;
  int epara = 0;
  bool mir = true;
  for (int i = 0; i < a; i++) {
    for (int j = 0; j < b; j++) {
      cin >> k;
      if (epara == 0) {
        modul = k % c;
        epara = 1;
      } else {
        if (modul != k % c) {
          mir = false;
        }
      }
      d.push_back(k);
    }
  }
  int sum = 0;
  if (!mir)
    cout << "-1";
  else {
    sort(d.begin(), d.end());
    if (d.size() % 2 == 1) {
      int pp = (d.size() - 1) / 2;
      for (int i = 0; i < d.size(); i++) {
        sum = sum + abs(d[i] - d[pp]) / c;
      }
      cout << sum;
    } else {
      int sum2 = 0;
      int pp = (d.size() + 1) / 2;
      for (int i = 0; i < d.size(); i++) {
        sum = sum + abs(d[i] - d[pp]) / c;
      }
      pp = (d.size() - 1) / 2;
      for (int i = 0; i < d.size(); i++) {
        sum2 = sum2 + abs(d[i] - d[pp]) / c;
      }
      cout << min(sum, sum2);
    }
  }
}
