#include <bits/stdc++.h>
using namespace std;
int ary[110][110];
int main(void) {
  ios_base::sync_with_stdio(0);
  int n, m, d;
  cin >> n >> m >> d;
  for (int i = 0; i < (n); i++)
    for (int j = 0; j < (m); j++) cin >> ary[i][j];
  int div = ary[0][0] % d;
  for (int i = 0; i < (n); i++)
    for (int j = 0; j < (m); j++)
      if (ary[i][j] % d != div) {
        cout << -1;
        return 0;
      }
  int mx = -1, mn = 100000000;
  for (int i = 0; i < (n); i++)
    for (int j = 0; j < (m); j++) {
      ary[i][j] = ary[i][j] / d;
      mn = min(ary[i][j], mn);
      mx = max(ary[i][j], mx);
    }
  int re = 999999999;
  for (int k = (mn); k < (mx + 1); k++) {
    int x = 0;
    for (int i = 0; i < (n); i++)
      for (int j = 0; j < (m); j++) {
        x += abs(k - ary[i][j]);
      }
    re = min(re, x);
  }
  cout << re << endl;
  return 0;
}
