#include <bits/stdc++.h>
using namespace std;
int a[1001][1001];
long long int find_ans(int n, int m, int curr, int d);
int main() {
  int n, m, d;
  cin >> n >> m >> d;
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      cin >> a[i][j];
    }
  }
  int curr = a[0][0];
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      if (abs(a[i][j] - curr) % d != 0) {
        cout << -1 << endl;
        return 0;
      }
    }
  }
  curr = curr - (curr / d) * d;
  long long int minm = 9999999999999999;
  long long int ans = curr;
  while (curr <= 10000) {
    long long temp = find_ans(n, m, curr, d);
    if (minm >= temp) {
      ans = temp;
      minm = temp;
    }
    curr += d;
  }
  cout << ans << endl;
  return 0;
}
long long int find_ans(int n, int m, int curr, int d) {
  long long int ans = 0;
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      ans += abs(a[i][j] - curr) / d;
    }
  }
  return ans;
}
