#include <bits/stdc++.h>
using namespace std;
const long long MOD = 1e6 + 3;
const long long INF = 2e9;
const long long N = 1e3 + 2;
const long long MAX = 2e5 + 2;
const long double EPS = 1e-6;
int a[N][N];
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  int n, m, d;
  cin >> n >> m >> d;
  for (long long i = 0; i < n; i++)
    for (long long j = 0; j < m; j++) cin >> a[i][j];
  int tmp = INF;
  for (long long i = 0; i < n; i++)
    tmp = min(tmp, *min_element(a[i], a[i] + m));
  for (long long i = 0; i < n; i++)
    for (long long j = 0; j < m; j++) a[i][j] -= tmp;
  for (long long i = 0; i < n; i++)
    for (long long j = 0; j < m; j++)
      if (a[i][j] % d) {
        cout << -1;
        return 0;
      }
  for (long long i = 0; i < n; i++)
    for (long long j = 0; j < m; j++) a[i][j] /= d;
  int sum = INF;
  for (long long i = 0; i < 10001; i++) {
    int ans = 0;
    for (long long i1 = 0; i1 < n; i1++)
      for (long long j1 = 0; j1 < m; j1++) ans += abs(a[i1][j1] - i);
    sum = min(sum, ans);
  }
  cout << sum;
}
