#include <bits/stdc++.h>
using namespace std;
const int vx[] = {1, 0, -1, 0}, vy[] = {0, 1, 0, -1};
const double EPS = 1e-9;
const int IMAX = 2147483647;
const int days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
const int daysleap[] = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int field[110][110];
int main() {
  int n, m, d;
  cin >> n >> m >> d;
  int prev, tar = 0;
  int MAX = 0, MIN = IMAX;
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
      cin >> field[j][i];
      MIN = min(MIN, field[j][i]);
      MAX = max(MAX, field[j][i]);
      tar += field[j][i];
      if ((i != 0 || j != 0) && (abs(prev - field[j][i]) % d != 0)) {
        cout << -1 << endl;
        return 0;
      }
      prev = field[j][i];
    }
  }
  int anst, ans = IMAX;
  for (int k = MIN; k <= MAX; k += d) {
    anst = 0;
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        anst += abs(field[j][i] - k) / d;
      }
    }
    ans = min(ans, anst);
  }
  cout << ans << endl;
  return 0;
}
