#include <bits/stdc++.h>
using namespace std;
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  long long int i, j, x;
  long long int n, m, d;
  cin >> n >> m >> d;
  int a[n + 5][m + 5];
  int sum = 0;
  for (i = 1; i <= n; i++) {
    for (j = 1; j <= m; j++) {
      cin >> a[i][j];
      sum += a[i][j];
    }
  }
  int te = (m * n), el;
  long long int ans = 1e14;
  for (x = 0; x <= 10000000; x++) {
    if ((sum + d * x) % te == 0) {
      el = (sum + d * x) / te;
      int moves = 0, check = 0;
      for (i = 1; i <= n; i++) {
        for (j = 1; j <= m; j++) {
          if (abs(a[i][j] - el) % d != 0) {
            check = 1;
            break;
          }
          moves = moves + abs(a[i][j] - el) / d;
        }
        if (check == 1) break;
      }
      if (check == 0) {
        if (moves < ans) ans = moves;
      }
    }
  }
  for (x = 0; x <= 10000000; x++) {
    if ((sum - d * x) % te == 0) {
      el = (sum - d * x) / te;
      int moves = 0, check = 0;
      for (i = 1; i <= n; i++) {
        for (j = 1; j <= m; j++) {
          if (abs(a[i][j] - el) % d != 0) {
            check = 1;
            break;
          }
          moves = moves + abs(a[i][j] - el) / d;
        }
        if (check == 1) break;
      }
      if (check == 0) {
        if (moves < ans) ans = moves;
      }
    }
  }
  if (ans == 1e14)
    cout << "-1\n";
  else
    cout << ans << "\n";
  return 0;
}
