#include <bits/stdc++.h>
using namespace std;
const int MAXN = 105;
int g[MAXN][MAXN];
int A[MAXN * MAXN];
int main() {
  int n, m, d;
  while (~scanf("%d%d%d", &n, &m, &d)) {
    bool flag = true;
    int s = 0;
    int len = 0;
    for (int i = 1; i <= n; i++)
      for (int j = 1; j <= m; j++) {
        scanf("%d", &g[i][j]);
        A[len++] = g[i][j];
        if (i == 1 && j == 1)
          s = g[i][j];
        else if (abs(g[i][j] - s) % d != 0)
          flag = false;
      }
    if (!flag)
      printf("-1\n");
    else {
      sort(A, A + len);
      int c = A[len / 2];
      int cc = -1;
      if (len % 2 == 0) cc = A[(len + 1) / 2];
      int ans = 0;
      for (int i = 1; i <= n; i++)
        for (int j = 1; j <= m; j++) ans += abs(g[i][j] - c) / d;
      int x = 0;
      for (int i = 1; i <= n; i++)
        for (int j = 1; j <= m; j++) x += abs(g[i][j] - c) / d;
      if (cc == -1)
        printf("%d\n", ans);
      else {
        printf("%d\n", min(ans, x));
      }
    }
  }
  return 0;
}
