#include <bits/stdc++.h>
using namespace std;
int main() {
  int n, m, d;
  cin >> n >> m >> d;
  int arr[n + 1][m + 1];
  int b[n * m + 1];
  int idx = 0;
  int modi = 0, i, j;
  for (i = 1; i <= n; i++)
    for (j = 1; j <= m; j++) {
      cin >> arr[i][j];
      if (i == 1 && j == 1) {
        modi = arr[i][j] % d;
      } else {
        if (modi != arr[i][j] % d) {
          cout << "-1\n";
          return 0;
        }
      }
      b[++idx] = arr[i][j];
    }
  sort(b + 1, b + idx + 1);
  int ele = b[idx / 2 + 1], sum = 0;
  for (i = 1; i <= n * m; i++) {
    sum += abs(b[i] - ele);
  }
  cout << sum / d << endl;
}
