#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 7;
const int mod = 1e9 + 7;
const int B = 317;
long long n, m, d;
long long mx;
long long res = 1e18;
long long a[111][111];
vector<long long> v[N];
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  cin >> n >> m >> d;
  long long mn = 1e18;
  long long mx = 0;
  bool f = false;
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= m; j++) {
      cin >> a[i][j];
      if (a[i][j] % d != a[1][1] % d) {
        cout << -1;
        return 0;
      }
      mx = max(mx, a[i][j]);
      mn = min(mn, a[i][j]);
    }
  }
  for (int i = mn; i <= mx; i++) {
    if (a[1][1] % d != i % d) continue;
    long long sum = 0;
    for (int j = 1; j <= n; j++) {
      for (int h = 1; h <= m; h++) {
        sum += abs(a[j][h] - i) / d;
      }
    }
    if (res > sum) res = sum;
  }
  if (res == 1e18) res = -1;
  cout << res;
}
