#include <bits/stdc++.h>
using namespace std;
const int MAXN = 111;
long long int n, m, d, f, a[MAXN][MAXN], inf = 1e5, s, k, p, q, A, B, mn = 1e6,
                                         mx, ans = 1e10;
long long int up(long long int x) {
  s = 0;
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      k = abs(x - a[i][j]);
      s += k / d;
    }
  }
  return s;
}
int main() {
  cin >> n >> m >> d;
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      cin >> a[i][j];
      mx = max(mx, a[i][j]);
      mn = min(mn, a[i][j]);
      if (!(i == 0 && j == 0) && f != a[i][j] % d) return cout << -1, 0;
      if (i == 0 && j == 0) f = a[i][j] % d;
    }
  }
  if (d == 1) {
    for (int i = mn; i <= mx; i++) {
      ans = min(ans, up(i));
    }
    return cout << ans, 0;
  }
  q = mx;
  p = mn;
  while (q - p > 2 * d) {
    A = p + d;
    B = q - d;
    if (up(A) >= up(B))
      p = A;
    else
      q = B;
  }
  cout << min(up(p), min(up(p + d), up(q))) << '\n';
}
