#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 5, M = 1e6, P = 1e9 + 7, INF = 0X3F3F3F3F;
int n, m, d, a[N];
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  cin >> n >> m >> d;
  int mn = 1e9;
  set<int> s;
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= m; j++) {
      cin >> a[(i - 1) * m + j];
      mn = min(mn, a[(i - 1) * m + j]);
      s.insert(a[(i - 1) * m + j] % d);
    }
  }
  if (s.size() != 1) {
    cout << -1 << '\n';
  } else {
    int ans = 1e9;
    for (int i = mn; i <= 10000; i += d) {
      int res = 0;
      for (int j = 1; j <= n * m; j++) {
        res += abs(i - a[j]) / d;
      }
      ans = min(ans, res);
    }
    cout << ans;
  }
  return 0;
}
