human
Solve in Python:
Little penguin Polo has an n × m matrix, consisting of integers. Let's index the matrix rows from 1 to n from top to bottom and let's index the columns from 1 to m from left to right. Let's represent the matrix element on the intersection of row i and column j as a_{ij}.

In one move the penguin can add or subtract number d from some matrix element. Find the minimum number of moves needed to make all matrix elements equal. If the described plan is impossible to carry out, say so.

-----Input-----

The first line contains three integers n, m and d (1 ≤ n, m ≤ 100, 1 ≤ d ≤ 10^4) — the matrix sizes and the d parameter. Next n lines contain the matrix: the j-th integer in the i-th row is the matrix element a_{ij} (1 ≤ a_{ij} ≤ 10^4).

-----Output-----

In a single line print a single integer — the minimum number of moves the penguin needs to make all matrix elements equal. If that is impossible, print "-1" (without the quotes).

-----Examples-----
Input
2 2 2
2 4
6 8

Output
4

Input
1 2 7
6 7

Output
-1
 Can you provide a Python code to find the minimum number of moves needed to make all matrix elements equal?
assistant
#Here is Python code to find the minimum number of moves needed to make all matrix elements equal.

import re
import itertools
from collections import Counter, deque

class Task:
    a = []
    d = 0
    answer = 0
	
    def getData(self):
        n, m, self.d = [int(x) for x in input().split(' ')]
        for _ in range(n):
            self.a += [int(x) for x in input().split(' ')]
        #inFile = open('input.txt', 'r')
        #inFile.readline().rstrip()
        #self.childs = inFile.readline().rstrip()

    def solve(self):
        a = self.a

        for x in a:
            if x % self.d != a[0] % self.d:
                self.answer = -1
                return
        
        a = [x // self.d for x in a]
        a.sort()
        
        d = [sum(a)] + [0 for _ in range(1, a[-1] + 1)]
        
        lessCurrentLevel = 0
        counter = Counter(a)
        
        for level in range(1, a[-1] + 1):
            lessCurrentLevel += counter[level - 1]
            d[level] = d[level - 1] + lessCurrentLevel - \
                    (len(a) - lessCurrentLevel)
        self.answer = min(d)

    def solve2(self):
        a, d = self.a, self.d
        for i in range(1, len(a)):
            if a[i] % d != a[0] % d:
                self.answer = -1
                return
        a = [x // d for x in a]
        d = [abs(a[0] - i) for i in range(10000 + 1)]
        for i in range(1, len(a)):
            for j in range(0, len(d)):
                d[j] += abs(a[i] - j)
        self.answer = min(d)

    def printAnswer(self):
        print(self.answer)
        #print(re.sub('[\[\],]', '', str(self.answer)))
        #outFile = open('output.txt', 'w')
        #outFile.write(self.answer)

task = Task()
task.getData()
task.solve()
task.printAnswer()