#include <bits/stdc++.h>
using namespace std;
long long mod(long long n) {
  if (n >= 0)
    return n;
  else
    return -n;
}
int main() {
  long long d, n, m, i, j, A[100][100], mine = 10000000000000,
                                        minee = 10000000000000, flag = 0;
  cin >> n >> m >> d;
  for (i = 0; i < n; i++) {
    for (j = 0; j < m; j++) {
      cin >> A[i][j];
    }
  }
  for (i = 0; i < n; i++) {
    for (j = 0; j < m; j++) {
      mine = min(mine, A[i][j]);
    }
  }
  for (i = 0; i < n; i++) {
    for (j = 0; j < m; j++) {
      A[i][j] -= mine;
      if (A[i][j] % d != 0) {
        flag = 1;
        break;
      }
      A[i][j] /= d;
    }
  }
  if (flag == 1)
    cout << -1;
  else {
    long long sum = 0;
    for (i = 0; i < n; i++) {
      for (j = 0; j < m; j++) {
        sum = sum + A[i][j];
      }
    }
    long long k;
    sum /= n * m;
    for (k = 0; k <= 10000; k++) {
      long long count = 0, flag1 = 0;
      for (i = 0; i < n; i++) {
        for (j = 0; j < m; j++) {
          if (count < minee) {
            count += mod(A[i][j] - k);
          } else {
            flag1 = 1;
            break;
          }
        }
        if (flag == 1) break;
      }
      minee = min(count, minee);
    }
    cout << minee;
  }
  return 0;
}
