/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
public class bbg
{
	public static int result;

public static ArrayList<Integer> [] graph;

public static int[]cats;

public static int vizitat[];
public static int x;

	public static void main (String[] args) throws java.lang.Exception
{

Scanner input=new Scanner(System.in);

HashMap<String, Integer> map1= new HashMap<String, Integer>();
HashMap<String, Integer> map2= new HashMap<String, Integer>();

	int n=input.nextInt();
	int m=input.nextInt();
	int d=input.nextInt();

	int sum=0;

	int mat[][]=new int[n][m];

	int v[]=new int[10002];

	for(int i=0;i<n;i++)
		for(int j=0;j<m;j++) {

			mat[i][j]=input.nextInt();

			sum+=mat[i][j];
			v[mat[i][j]]++;

		}

		int centru=(int)Math.round((double)sum/(double)(n*m));

		int result=0;

	//	System.out.println("centru="+centru);

		int x=1;

		int max=Integer.MAX_VALUE;
		int poz=-1;

		for(int i=1;i<=10000;i++)
		if(v[i]>0) {

		    if(Math.abs(i-centru)<max) {max=Math.abs(i-centru); poz=i;}

		}

		//	System.out.println("poz="+poz);

		for(int i=1;i<=10000;i++){

		    if(v[i]!=0 )

		    {
		        if((Math.abs(i-poz))%d!=0) {

		           // System.out.println("eroare="+i);
		            x=0;i=10001;}

		        else result+=(Math.abs(i-poz)*v[i])/d;

		    }

		}

		if(x==0) System.out.println(-1);
		else System.out.println(result);

}

			}


/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
public class bbg
{
	public static int result;

public static ArrayList<Integer> [] graph;

public static int[]cats;

public static int vizitat[];
public static int x;

	public static void main (String[] args) throws java.lang.Exception
{

Scanner input=new Scanner(System.in);

HashMap<String, Integer> map1= new HashMap<String, Integer>();
HashMap<String, Integer> map2= new HashMap<String, Integer>();

	int n=input.nextInt();
	int m=input.nextInt();
	int d=input.nextInt();

	int sum=0;

	int mat[][]=new int[n][m];

	int v[]=new int[10002];

	for(int i=0;i<n;i++)
		for(int j=0;j<m;j++) {

			mat[i][j]=input.nextInt();

			v[mat[i][j]]++;

		}

		int x=1;

		int max=Integer.MAX_VALUE;
		int poz=-1;

		int rasp=Integer.MAX_VALUE;

		for(int centru=1;centru<=10000;centru++){

		    rasp=0;
		    x=1;

		    for(int j=1;j<=10000;j++){

		        if(v[j]>0) {

		            //System.out.println(j+" "+v[j]);

		            if(Math.abs(j-centru)%d!=0) {x=0;j=10001;}

		            else {rasp+=Math.abs(centru-j)*v[j]/d;
		          //  System.out.println(centru+" "+j+" "+rasp);
		            }

		    }

		}

		  if(x==1)
		    max=Math.min(max,rasp);

		}

		System.out.println(max);

}

}


/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
public class bbg
{
	public static int result;

public static ArrayList<Integer> [] graph;

public static int[]cats;

public static int vizitat[];
public static int x;

	public static void main (String[] args) throws java.lang.Exception
{

Scanner input=new Scanner(System.in);

HashMap<String, Integer> map1= new HashMap<String, Integer>();
HashMap<String, Integer> map2= new HashMap<String, Integer>();

	int n=input.nextInt();
	int m=input.nextInt();
	int d=input.nextInt();

	int sum=0;

	int mat[][]=new int[n][m];

	int v[]=new int[10002];

	for(int i=0;i<n;i++)
		for(int j=0;j<m;j++) {

			mat[i][j]=input.nextInt();

			v[mat[i][j]]++;

	sum++;

		}

		int media=sum/(n*m);

		int contor=0;
		int x=1;

		int max=Integer.MAX_VALUE;
		int poz=-1;

		int rasp=Integer.MAX_VALUE;

		for(int centru=Math.max(0,sum/2);centru<=Math.min(10000,sum*2);centru++){

		    rasp=0;
		    x=1;

		    for(int j=1;j<=10000;j++){

		        if(v[j]>0) {

		            //System.out.println(j+" "+v[j]);

		            if(Math.abs(j-centru)%d!=0) {x=0;j=10001;}

		            else {rasp+=Math.abs(centru-j)*v[j]/d;
		          //  System.out.println(centru+" "+j+" "+rasp);
		            }

		    }

		}

		  if(x==1){contor++;
		  //System.out.println("contor="+contor);
		    max=Math.min(max,rasp);}

		}

		if(contor==0) System.out.println(-1);
		else
		System.out.println(max);

}

}


/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
public class bbg
{
	public static int result;

public static ArrayList<Integer> [] graph;

public static int[]cats;

public static int vizitat[];
public static int x;

	public static void main (String[] args) throws java.lang.Exception
{

Scanner input=new Scanner(System.in);

HashMap<String, Integer> map1= new HashMap<String, Integer>();
HashMap<String, Integer> map2= new HashMap<String, Integer>();

	int n=input.nextInt();
	int m=input.nextInt();
	int d=input.nextInt();

	int sum=0;

	int c=0;

	int mat[][]=new int[n][m];

	int v[]=new int[10002];

	int a[]=new int[n*m];

	for(int i=0;i<n;i++)
		for(int j=0;j<m;j++) {

			mat[i][j]=input.nextInt();

			v[mat[i][j]]++;

			a[c]=	mat[i][j];

			   c++;

	sum+=mat[i][j];;

		}

		Arrays.sort(a);

	int	media=a[(n*m)/2];

		//System.out.println("sum="+media);

		int contor=0;
		int x=1;

		int max=Integer.MAX_VALUE;
		int poz=-1;

		int rasp=Integer.MAX_VALUE;

int centru=media;

		    rasp=0;
		    x=1;

		    for(int j=1;j<=10000;j++){

		        if(v[j]>0) {

		            //System.out.println(j+" "+v[j]);

		            if(Math.abs(j-centru)%d!=0) {x=0;j=10001;}

		            else {rasp+=Math.abs(centru-j)*v[j]/d;
		          //  System.out.println(centru+" "+j+" "+rasp);
		            }

		    }

		}

		  if(x==1){contor++;
		  //System.out.println("contor="+contor);
		    max=Math.min(max,rasp);}

		if(contor==0) System.out.println(-1);
		else
		System.out.println(max);

}

}


import java.io.*;
import java.lang.*;
import java.util.*;
import java.math.*;

public class code
{
	static class FastReader
    {
        BufferedReader br;
        StringTokenizer st;

        public FastReader()
        {
            br = new BufferedReader(new
                     InputStreamReader(System.in));
        }

        String next()
        {
            while (st == null || !st.hasMoreElements())
            {
                try
                {
                    st = new StringTokenizer(br.readLine());
                }
                catch (IOException  e)
                {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt()
        {
            return Integer.parseInt(next());
        }

        long nextLong()
        {
            return Long.parseLong(next());
        }

        double nextDouble()
        {
            return Double.parseDouble(next());
        }

        String nextLine()
        {
            String str = "";
            try
            {
                str = br.readLine();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            return str;
        }
    }

	public static void main(String args[])throws IOException
	{
		FastReader scn = new FastReader();

		int n = scn.nextInt();
		int m = scn.nextInt();
		int d = scn.nextInt();

		int[] list = new int[m*n];
		for(int i = 0; i < n; i++)
		{
			for(int j = 0; j < m; j++)
			{
                if(i==0 && j==0)
				    list[i*m + j] = scn.nextInt();
                else
                {
                    list[i*m + j] = scn.nextInt() - list[0];

    				if(Math.abs(list[i*m+j])%d != 0)
    				{
    					System.out.println(-1);
    					return;
    				}
                }
			}
		}

        list[0] = 0;
		Arrays.sort(list);

        long sum;
        if(n*m % 2 == 1)
        {
            int median = list[(n*m)/2];
            sum = 0;
            for(int value: list)
            {
                sum = sum + Math.abs(value - median);
            }
        }
        else
        {
            int median1 = list[(n*m)/2 - 1];
            int median2 = list[(n*m)/2];
            long sum1 = 0, sum2 = 0;
            for(int value: list)
            {
                sum1 = sum1 + Math.abs(value - median1);
                sum2 = sum2 + Math.abs(value - median2);
            }
            sum = Math.min(sum1, sum2);
        }

		System.out.println(sum/d);
	}
}

class Pair implements Comparable<Pair>
{
	long p, h;
	public Pair(long p, long h)
	{
		this.p = p;
		this.h = h;
	}

	public int compareTo(Pair pair)
	{
		if(this.p < pair.p)
			return -1;
		else if(this.p > pair.p)
			return 1;
		else
			return 0;
	}
}


import java.io.*;
import java.lang.*;
import java.util.*;
import java.math.*;

public class code
{
	static class FastReader
    {
        BufferedReader br;
        StringTokenizer st;

        public FastReader()
        {
            br = new BufferedReader(new
                     InputStreamReader(System.in));
        }

        String next()
        {
            while (st == null || !st.hasMoreElements())
            {
                try
                {
                    st = new StringTokenizer(br.readLine());
                }
                catch (IOException  e)
                {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt()
        {
            return Integer.parseInt(next());
        }

        long nextLong()
        {
            return Long.parseLong(next());
        }

        double nextDouble()
        {
            return Double.parseDouble(next());
        }

        String nextLine()
        {
            String str = "";
            try
            {
                str = br.readLine();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            return str;
        }
    }

	public static void main(String args[])throws IOException
	{
		FastReader scn = new FastReader();

		int n = scn.nextInt();
		int m = scn.nextInt();
		int d = scn.nextInt();

		int[] list = new int[m*n];
		for(int i = 0; i < n; i++)
		{
			for(int j = 0; j < m; j++)
			{
                if(i==0 && j==0)
				    list[i*m + j] = scn.nextInt();
                else
                    list[i*m + j] = scn.nextInt() - list[0];

				if(Math.abs(list[i*m+j])%d != 0)
				{
					System.out.println(-1);
					return;
				}
			}
		}

        list[0] = 0;
		Arrays.sort(list);

        long sum;
        if(n*m % 2 == 1)
        {
            int median = list[(n*m)/2];
            sum = 0;
            for(int value: list)
            {
                sum = sum + Math.abs(value - median);
            }
        }
        else
        {
            int median1 = list[(n*m)/2 - 1];
            int median2 = list[(n*m)/2];
            long sum1 = 0, sum2 = 0;
            for(int value: list)
            {
                sum1 = sum1 + Math.abs(value - median1);
                sum2 = sum2 + Math.abs(value - median2);
            }
            sum = Math.min(sum1, sum2);
        }

		System.out.println(sum/d);
	}
}

class Pair implements Comparable<Pair>
{
	long p, h;
	public Pair(long p, long h)
	{
		this.p = p;
		this.h = h;
	}

	public int compareTo(Pair pair)
	{
		if(this.p < pair.p)
			return -1;
		else if(this.p > pair.p)
			return 1;
		else
			return 0;
	}
}


import java.io.*;
import java.lang.*;
import java.util.*;
import java.math.*;

public class code
{
	static class FastReader
    {
        BufferedReader br;
        StringTokenizer st;

        public FastReader()
        {
            br = new BufferedReader(new
                     InputStreamReader(System.in));
        }

        String next()
        {
            while (st == null || !st.hasMoreElements())
            {
                try
                {
                    st = new StringTokenizer(br.readLine());
                }
                catch (IOException  e)
                {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt()
        {
            return Integer.parseInt(next());
        }

        long nextLong()
        {
            return Long.parseLong(next());
        }

        double nextDouble()
        {
            return Double.parseDouble(next());
        }

        String nextLine()
        {
            String str = "";
            try
            {
                str = br.readLine();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            return str;
        }
    }

	public static void main(String args[])throws IOException
	{
		FastReader scn = new FastReader();

		int n = scn.nextInt();
		int m = scn.nextInt();
		int d = scn.nextInt();

		int[] list = new int[m*n];
		for(int i = 0; i < n; i++)
		{
			for(int j = 0; j < m; j++)
			{
                if(i==0 && j==0)
				    list[i*m + j] = scn.nextInt();
                else
                    list[i*m + j] = scn.nextInt() - list[0];

				if(Math.abs(list[i*m+j])%d != 0)
				{
					System.out.println(-1);
					return;
				}
			}
		}

        list[0] = 0;
		Arrays.sort(list);

        int median = list[(n*m)/2];
		long sum = 0;
		for(int x: list)
		{
			sum = sum + Math.abs(x - median);
		}

		System.out.println(sum/d);

	}
}

class Pair implements Comparable<Pair>
{
	long p, h;
	public Pair(long p, long h)
	{
		this.p = p;
		this.h = h;
	}

	public int compareTo(Pair pair)
	{
		if(this.p < pair.p)
			return -1;
		else if(this.p > pair.p)
			return 1;
		else
			return 0;
	}
}


import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
import java.util.Arrays;

public class Solution {
//    ----------------------------------------------------------------------------

    public static void main(String[] args) throws IOException {

        //IF INPUT-OUTPUT is via files. uncomment use the below 3 lines of code. comment out the next 4
        //     File file = new File("input.txt"); // here input.txt and output.txt being the file names
        //   InputReader in = new InputReader(new FileInputStream(file));
        //    PrintWriter out = new PrintWriter(new FileOutputStream("output.txt"));
        //ELSE
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        Task solver = new Task();
        solver.solve(1, in, out);
        out.close();
    }

    static class Task {

        public void solve(int testNumber, InputReader in, PrintWriter out) {
            int n = in.nextInt();
            int m = in.nextInt();
            int d = in.nextInt();
            int a[] = new int[n * m];
            a[0] = in.nextInt();

            int x = a[0] % d;
            boolean nohoi = false;

            //Main Principle
            // if n%d == something. (n+d)%d  and (n-d)%d will be that as well
            //ex. 5%2 = 1  , (5+2)%2 == 1 , (5-2)%2 == 1
            //ex. 13%5 = 3  , (13+5)%5 == 3 , (13-5)%5 == 3
            // So . if they all need to be equal.(by adding or sub d)
            // they need to have same %d
            for (int i = 1; i < n * m; i++) {

                a[i] = in.nextInt();

                if (a[i] % d != x) {

                    nohoi = true;
                }

            }
            if (nohoi) {

                out.println("-1");
            } else {
                Arrays.sort(a);
                int median = a[n * m / 2];
                int ans = 0;
                for (int i = 0; i < n * m; i++) {
                    ans += Math.abs(a[i] - median) / d;

                }
                out.println(ans);
            }

        }

    }

//    ----------------------------------------------------------------------------
    // MAIN - INPUT - OUTPUT
    static class InputReader {

        public BufferedReader reader;
        public StringTokenizer tokenizer;

        public InputReader(InputStream stream) {
            reader = new BufferedReader(new InputStreamReader(stream), 32768);
            tokenizer = null;
        }

        public String next() {
            while (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    tokenizer = new StringTokenizer(reader.readLine());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken();
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }

        public Double nextDouble() {
            return Double.parseDouble(next());
        }

        public long nextLong() {
            return Long.parseLong(next());
        }

        public int[] nextIntArray(int arraySize) {
            int array[] = new int[arraySize];

            for (int i = 0; i < arraySize; i++) {
                array[i] = nextInt();
            }

            return array;
        }

    }
}


import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
import java.util.Arrays;

public class Solution {
//    ----------------------------------------------------------------------------

    public static void main(String[] args) throws IOException {

        //IF INPUT-OUTPUT is via files. uncomment use the below 3 lines of code. comment out the next 4
        //     File file = new File("input.txt"); // here input.txt and output.txt being the file names
        //   InputReader in = new InputReader(new FileInputStream(file));
        //    PrintWriter out = new PrintWriter(new FileOutputStream("output.txt"));
        //ELSE
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        Task solver = new Task();
        solver.solve(1, in, out);
        out.close();
    }

    static class Task {

        public void solve(int testNumber, InputReader in, PrintWriter out) {
            int n = in.nextInt();
            int m = in.nextInt();
            int d = in.nextInt();
            int a[] = new int[n * m];
            a[0] = in.nextInt();

            int x = a[0] % d;
            boolean nohoi = false;

            for (int i = 1; i < n * m; i++) {

                a[i] = in.nextInt();

                if (a[i] % d != x) {

                    nohoi = true;
                }

            }
            if (nohoi) {

                out.println("-1");
            } else {
                Arrays.sort(a);
                int median = a[n * m / 2];
                int ans = 0;
                for (int i = 0; i < n * m; i++) {
                    ans += Math.abs(a[i] - median)/d;

                }
                out.println(ans);
            }

        }

    }

//    ----------------------------------------------------------------------------
    // MAIN - INPUT - OUTPUT
    static class InputReader {

        public BufferedReader reader;
        public StringTokenizer tokenizer;

        public InputReader(InputStream stream) {
            reader = new BufferedReader(new InputStreamReader(stream), 32768);
            tokenizer = null;
        }

        public String next() {
            while (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    tokenizer = new StringTokenizer(reader.readLine());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken();
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }

        public Double nextDouble() {
            return Double.parseDouble(next());
        }

        public long nextLong() {
            return Long.parseLong(next());
        }

        public int[] nextIntArray(int arraySize) {
            int array[] = new int[arraySize];

            for (int i = 0; i < arraySize; i++) {
                array[i] = nextInt();
            }

            return array;
        }

    }
}


import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
import java.util.Arrays;

public class Solution {
//    ----------------------------------------------------------------------------

    public static void main(String[] args) throws IOException {

        //IF INPUT-OUTPUT is via files. uncomment use the below 3 lines of code. comment out the next 4
        //     File file = new File("input.txt"); // here input.txt and output.txt being the file names
        //   InputReader in = new InputReader(new FileInputStream(file));
        //    PrintWriter out = new PrintWriter(new FileOutputStream("output.txt"));
        //ELSE
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        Task solver = new Task();
        solver.solve(1, in, out);
        out.close();
    }

    static class Task {

        public void solve(int testNumber, InputReader in, PrintWriter out) {
            int n = in.nextInt();
            int m = in.nextInt();
            int d = in.nextInt();
            int a[] = new int[n * m];
            a[0] = in.nextInt();

            int x = a[0] % d;
            boolean nohoi = false;

            for (int i = 1; i < n * m; i++) {

                a[i] = in.nextInt();

                if (a[i] % d != x) {

                    nohoi = true;
                }

            }
            if (nohoi) {

                out.println("-1");
            } else {
                Arrays.sort(a);
                int median = a[n * m / 2];
                int ans = 0;
                for (int i = 0; i < n * m; i++) {
                    ans += Math.abs(a[i] - median);

                }
                out.println(ans/2);
            }

        }

    }

//    ----------------------------------------------------------------------------
    // MAIN - INPUT - OUTPUT
    static class InputReader {

        public BufferedReader reader;
        public StringTokenizer tokenizer;

        public InputReader(InputStream stream) {
            reader = new BufferedReader(new InputStreamReader(stream), 32768);
            tokenizer = null;
        }

        public String next() {
            while (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    tokenizer = new StringTokenizer(reader.readLine());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken();
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }

        public Double nextDouble() {
            return Double.parseDouble(next());
        }

        public long nextLong() {
            return Long.parseLong(next());
        }

        public int[] nextIntArray(int arraySize) {
            int array[] = new int[arraySize];

            for (int i = 0; i < arraySize; i++) {
                array[i] = nextInt();
            }

            return array;
        }

    }
}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.util.Random;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskB solver = new TaskB();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskB {
        public void solve(int testNumber, InputReader in, PrintWriter out) {
            int n = in.nextInt() * in.nextInt();
            long d = in.nextInt();
            long[] ar = new long[n];
            long r = -1;
            for (int i = 0; i < n; i++) {
                ar[i] = in.nextInt();
                if (r == -1)
                    r = ar[i] % d;
                else if (r != ar[i] % d) {
                    out.println(-1);
                    return;
                }
            }
            for (int i = 0; i < n; i++) {
                ar[i] = (ar[i] - r) / d;
            }

            ArrayUtils.shuffleLongArray(ar);
            Arrays.sort(ar);

            long s = ar[0];
            long minSum = Integer.MAX_VALUE;
            long bestPoint = -1;
            for (int i = 0; i < n - 1; i++) {
                long x;
                if (i + 1 < n - (i + 1)) {
                    x = ar[i + 1];
                } else {
                    x = ar[i];
                }

                long l = (i + 1 - (n - i - 1)) * x - 2 * s;
                if (l < minSum) {
                    minSum = l;
                    bestPoint = x;
                }

                s += ar[i + 1];
            }

            long ans = 0;
            for (int i = 0; i < n; i++) {
                ans += Math.abs(ar[i] - bestPoint);
            }
            out.println(ans);
        }

    }

    static class InputReader {
        StringTokenizer st;
        BufferedReader br;

        public InputReader(InputStream is) {
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            this.br = br;
        }

        public String next() {
            if (st == null || !st.hasMoreTokens()) {
                String nextLine = null;
                try {
                    nextLine = br.readLine();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                if (nextLine == null)
                    return null;
                st = new StringTokenizer(nextLine);
            }
            return st.nextToken();
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }

    }

    static final class ArrayUtils {
        static Random rnd = new Random();

        public static void shuffleLongArray(long[] ar) {
            for (int i = ar.length - 1; i > 0; i--) {
                int index = rnd.nextInt(i + 1);
                long a = ar[index];
                ar[index] = ar[i];
                ar[i] = a;
            }
        }

    }
}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.util.Random;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskB solver = new TaskB();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskB {
        public void solve(int testNumber, InputReader in, PrintWriter out) {
            int n = in.nextInt() * in.nextInt();
            long d = in.nextInt();
            long[] ar = new long[n];
            long r = -1;
            for (int i = 0; i < n; i++) {
                ar[i] = in.nextInt();
                if (r == -1)
                    r = ar[i] % d;
                else if (r != ar[i] % d) {
                    out.println(-1);
                    return;
                }
            }
            for (int i = 0; i < n; i++) {
                ar[i] = (ar[i] - r) / d;
            }

            ArrayUtils.shuffleLongArray(ar);
            Arrays.sort(ar);

            long s = ar[0];
            long minSum = Integer.MAX_VALUE;
            long bestPoint = -1;
            for (int i = 0; i < n - 1; i++) {
                long x;
                if (i + 1 < n - (i + 1)) {
                    x = ar[i + 1];
                } else {
                    x = ar[i];
                }

                long l = (i + 1 - (n - i - 1)) * x - 2 * s;
                if (l < minSum) {
                    minSum = l;
                    bestPoint = x;
                }
            }

            long ans = 0;
            for (int i = 0; i < n; i++) {
                ans += Math.abs(ar[i] - bestPoint);
            }
            out.println(ans);
        }

    }

    static class InputReader {
        StringTokenizer st;
        BufferedReader br;

        public InputReader(InputStream is) {
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            this.br = br;
        }

        public String next() {
            if (st == null || !st.hasMoreTokens()) {
                String nextLine = null;
                try {
                    nextLine = br.readLine();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                if (nextLine == null)
                    return null;
                st = new StringTokenizer(nextLine);
            }
            return st.nextToken();
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }

    }

    static final class ArrayUtils {
        static Random rnd = new Random();

        public static void shuffleLongArray(long[] ar) {
            for (int i = ar.length - 1; i > 0; i--) {
                int index = rnd.nextInt(i + 1);
                long a = ar[index];
                ar[index] = ar[i];
                ar[i] = a;
            }
        }

    }
}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.util.Random;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskB solver = new TaskB();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskB {
        public void solve(int testNumber, InputReader in, PrintWriter out) {
            int n = in.nextInt() * in.nextInt();
            long d = in.nextInt();
            long[] ar = new long[n];
            long r = -1;
            for (int i = 0; i < n; i++) {
                ar[i] = in.nextInt();
                if (r == -1)
                    r = ar[i] % d;
                else if (r != ar[i] % d) {
                    out.println(-1);
                    return;
                }
            }
            {
                boolean allEq = true;
                for (int i = 1; i < n; i++) {
                    if (ar[0] != ar[i]) {
                        allEq = false;
                        break;
                    }
                }
                if (allEq) {
                    out.println(0);
                    return;
                }
            }
            for (int i = 0; i < n; i++) {
                ar[i] = (ar[i] - r) / d;
            }

            ArrayUtils.shuffleLongArray(ar);
            Arrays.sort(ar);

            long s = ar[0];
            long minSum = Integer.MAX_VALUE;
            long bestPoint = -1;
            for (int i = 0; i < n - 1; i++) {
                long x;
                if (i + 1 < n - (i + 1)) {
                    x = ar[i + 1];
                } else {
                    x = ar[i];
                }

                long l = (i + 1 - (n - i - 1)) * x - 2 * s;
                if (l < minSum) {
                    minSum = l;
                    bestPoint = x;
                }

                s += ar[i + 1];
            }

            long ans = 0;
            for (int i = 0; i < n; i++) {
                ans += Math.abs(ar[i] - bestPoint);
            }
            out.println(ans);
        }

    }

    static class InputReader {
        StringTokenizer st;
        BufferedReader br;

        public InputReader(InputStream is) {
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            this.br = br;
        }

        public String next() {
            if (st == null || !st.hasMoreTokens()) {
                String nextLine = null;
                try {
                    nextLine = br.readLine();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                if (nextLine == null)
                    return null;
                st = new StringTokenizer(nextLine);
            }
            return st.nextToken();
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }

    }

    static final class ArrayUtils {
        static Random rnd = new Random();

        public static void shuffleLongArray(long[] ar) {
            for (int i = ar.length - 1; i > 0; i--) {
                int index = rnd.nextInt(i + 1);
                long a = ar[index];
                ar[index] = ar[i];
                ar[i] = a;
            }
        }

    }
}


import java.util.*;
import java.io.*;
public class Polo_the_Penguin_and_Matrix
{
	public static void main(String args[]) throws Exception
	{
		BufferedReader f=new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st=new StringTokenizer(f.readLine());
		int rows=Integer.parseInt(st.nextToken());
		int cols=Integer.parseInt(st.nextToken());
		int change=Integer.parseInt(st.nextToken());
		int[][] arr=new int[rows][cols];
		for(int y=0;y<rows;y++)
		{
			st=new StringTokenizer(f.readLine());
			for(int x=0;x<cols;x++)
				arr[y][x]=Integer.parseInt(st.nextToken());
		}
		int min=Integer.MAX_VALUE;
		for(int y=0;y<rows;y++)
			for(int x=0;x<cols;x++)
			{
				int temp=0;
				boolean flag=true;
				loop: for(int a=0;a<rows;a++)
					for(int b=0;b<cols;b++)
						if(Math.abs(arr[y][x]-arr[a][b])%change!=0)
						{
							flag=false;
							break loop;
						}
						else
							temp+=Math.abs(arr[y][x]-arr[a][b])/change;
				if(flag) min=Math.min(min,temp);
			}
		System.out.println(min==Integer.MAX_VALUE?-1:min);
	}
}


import java.util.*;
import java.io.*;
public class Polo_the_Penguin_and_Matrix
{
	public static void main(String args[]) throws Exception
	{
		BufferedReader f=new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st=new StringTokenizer(f.readLine());
		int rows=Integer.parseInt(st.nextToken());
		int cols=Integer.parseInt(st.nextToken());
		int change=Integer.parseInt(st.nextToken());
		int[] arr=new int[rows*cols];
		for(int x=0;x<rows;x++)
		{
			st=new StringTokenizer(f.readLine());
			for(int y=0;y<cols;y++)
				arr[x*cols+y]=Integer.parseInt(st.nextToken());
		}
		Arrays.sort(arr);
		boolean flag=true;
		for(int x=1;x<arr.length;x++)
			if((arr[x]-arr[x-1])%change!=0)
				flag=false;
		if(!flag)
			System.out.println(-1);
		else
		{
			long temp=0;
			for(int x=1;x<arr.length;x++)
				temp+=Math.abs(arr[0]-arr[x]);
			long min=temp/change;
			for(int x=1;x<arr.length;x++)
			{
				int tempo=arr[x]-arr[x-1];
				temp-=tempo*(arr.length-x);
				temp+=tempo*x;
				min=Math.min(min,temp/change);
			}
			System.out.println(min);
		}
	}
}


import java.util.*;
import java.io.*;
public class Polo_the_Penguin_and_Matrix
{
	public static void main(String args[]) throws Exception
	{
		BufferedReader f=new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st=new StringTokenizer(f.readLine());
		int rows=Integer.parseInt(st.nextToken());
		int cols=Integer.parseInt(st.nextToken());
		int change=Integer.parseInt(st.nextToken());
		int[] arr=new int[rows*cols];
		for(int x=0;x<rows;x++)
		{
			st=new StringTokenizer(f.readLine());
			for(int y=0;y<cols;y++)
				arr[x*cols+y]=Integer.parseInt(st.nextToken());
		}
		Arrays.sort(arr);
		boolean flag=true;
		for(int x=1;x<arr.length;x++)
			if((arr[x]-arr[x-1])%change!=0)
				flag=false;
		if(!flag)
			System.out.println(-1);
		else
		{
			long temp=0;
			for(int x=1;x<arr.length;x++)
				temp+=Math.abs(arr[0]-arr[x]);
			long min=temp/change;
			for(int x=1;x<arr.length;x++)
			{
				int tempo=arr[x]-arr[x-1];
				temp-=tempo*(arr.length-x);
				temp+=tempo*x;
				min=Math.min(min,temp);
			}
			System.out.println(min/change);
		}
	}
}


import java.io.*;
import java.util.*;

public class Main{
	public static class FastReader {
		BufferedReader br;
		StringTokenizer st;

		public FastReader() {
			br = new BufferedReader(new InputStreamReader(System.in));
		}

		String next() {
			while (st == null || !st.hasMoreTokens()) {
				try {
					st = new StringTokenizer(br.readLine());
				} catch (Exception r) {
					r.printStackTrace();
				}
			}
			return st.nextToken();
		}

		int nextInt() {
			return Integer.parseInt(next());
		}

		double nextDouble() {
			return Double.parseDouble(next());
		}

		long nextLong() {
			return Long.parseLong(next());
		}

		String nextLine() {
			String str = "";
			try {
				str = br.readLine();
			} catch (Exception r) {
				r.printStackTrace();
			}
			return str;
		}
	}

	public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out));
	static long mod = (long) (1e9+7);
    static final long N = (long) (1e5 + 10);

	public static void main(String[] args) {
		FastReader sc = new FastReader();

		int n = sc.nextInt();
		int m = sc.nextInt();
		int d = sc.nextInt();

		Integer[] tab = new Integer[n*m+1];
		long[] pre = new long[n*m+1];
		int k = 1;
		boolean found = false;
		int val = -1;
		for(int i=0;i<n && !found;++i) {
			for(int j=0;j<m && !found;++j) {
				tab[k++] = sc.nextInt();
				pre[k-1] += pre[k-2]+tab[k-1].intValue();
				if(val > 0 && val != tab[k-1].intValue()%d)
					found = true;
				else val = tab[k-1].intValue()%d;
			}
		}
		if(found) out.println(-1);
		else {
			long ans = Integer.MAX_VALUE;
			for(int i=1;i<=n*m;++i) {
				long sum = 1L*i*tab[i].intValue() - pre[i] + pre[n*m] - pre[i] - 1L*(n*m-i)*tab[i].intValue();
				ans = Math.min(ans, sum/d);
			}
			out.println(ans);
		}

	    out.close();
	}

}


import java.io.*;
import java.util.*;

public class Main{
	public static class FastReader {
		BufferedReader br;
		StringTokenizer st;

		public FastReader() {
			br = new BufferedReader(new InputStreamReader(System.in));
		}

		String next() {
			while (st == null || !st.hasMoreTokens()) {
				try {
					st = new StringTokenizer(br.readLine());
				} catch (Exception r) {
					r.printStackTrace();
				}
			}
			return st.nextToken();
		}

		int nextInt() {
			return Integer.parseInt(next());
		}

		double nextDouble() {
			return Double.parseDouble(next());
		}

		long nextLong() {
			return Long.parseLong(next());
		}

		String nextLine() {
			String str = "";
			try {
				str = br.readLine();
			} catch (Exception r) {
				r.printStackTrace();
			}
			return str;
		}
	}

	public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out));
	static long mod = (long) (1e9+7);
    static final long N = (long) (1e5 + 10);

	public static void main(String[] args) {
		FastReader sc = new FastReader();

		int n = sc.nextInt();
		int m = sc.nextInt();
		int d = sc.nextInt();

		List<Long> tab = new ArrayList<>();
		tab.add(0L);
		long[] pre = new long[n*m+1];
		int k = 1;
		boolean found = false;
		long val = -1;
		for(int i=0;i<n && !found;++i) {
			for(int j=0;j<m && !found;++j) {
				tab.add(sc.nextLong());
				if(val > 0 && val != tab.get(tab.size()-1)%d)
					found = true;
				else val = tab.get(tab.size()-1)%d;
			}
		}

		Collections.sort(tab);
		for(int i=1;i<=n*m;++i) pre[i]=pre[i-1]+tab.get(i);
		if(found) out.println(-1);
		else {

			long ans = Integer.MAX_VALUE;
			for(int i=1;i<=n*m;++i) {
				long sum = 1L*i*tab.get(i) - pre[i] + pre[n*m] - pre[i] - 1L*(n*m-i)*tab.get(i);

				ans = Math.min(ans, sum/d);
			}
			out.println(ans);
		}

	    out.close();
	}

}


import java.io.*;
import java.util.*;

public class Main{
	public static class FastReader {
		BufferedReader br;
		StringTokenizer st;

		public FastReader() {
			br = new BufferedReader(new InputStreamReader(System.in));
		}

		String next() {
			while (st == null || !st.hasMoreTokens()) {
				try {
					st = new StringTokenizer(br.readLine());
				} catch (Exception r) {
					r.printStackTrace();
				}
			}
			return st.nextToken();
		}

		int nextInt() {
			return Integer.parseInt(next());
		}

		double nextDouble() {
			return Double.parseDouble(next());
		}

		long nextLong() {
			return Long.parseLong(next());
		}

		String nextLine() {
			String str = "";
			try {
				str = br.readLine();
			} catch (Exception r) {
				r.printStackTrace();
			}
			return str;
		}
	}

	public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out));
	static long mod = (long) (1e9+7);
    static final long N = (long) (1e5 + 10);

	public static void main(String[] args) {
		FastReader sc = new FastReader();

		int n = sc.nextInt();
		int m = sc.nextInt();
		int d = sc.nextInt();

		List<Long> tab = new ArrayList<>();
		tab.add(0L);
		long[] pre = new long[(n*m)+1];
		int k = 1;
		boolean found = false;
		long val = -1;
		for(int i=0;i<n && !found;++i) {
			for(int j=0;j<m && !found;++j) {
				tab.add(sc.nextLong());
				if(val > 0 && val != tab.get(tab.size()-1)%d)
					found = true;
				else val = tab.get(tab.size()-1)%d;
			}
		}

		if(found) out.println(-1);
		else {
			Collections.sort(tab);
			for(int i=1;i<=n*m;++i) pre[i]=pre[i-1]+tab.get(i);
			long ans = Integer.MAX_VALUE;
			for(int i=1;i<=n*m;++i) {
				long sum = 1L*i*tab.get(i) - pre[i] + pre[n*m] - pre[i] - 1L*(n*m-i)*tab.get(i);

				ans = Math.min(ans, sum/d);
			}
			out.println(ans);
		}

	    out.close();
	}

}


import java.util.*;
public class Main {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt() * sc.nextInt();
        int d = sc.nextInt();
        int a[] = new int[n];
        for(int i=0; i<n; i++)
            a[i] = sc.nextInt();

        boolean flag = true;
        int midd = n / 2;
        int count = 0;
        Arrays.sort(a);
        int dp[] = new int[n];
        for(int i=0; i<n; i++)
            dp[i] = Math.abs(a[i] - a[midd]);
        for(int i=0; i<n; i++) {
            if(dp[i] % d == 0)
                count += dp[i] / d;
            else {
                flag = false;
                break;
            }
        }
        System.out.println(flag ? count : "-1");
    }
}


import java.util.*;
public class Main {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int m = sc.nextInt();
        int d = sc.nextInt();
        int l = n * m;
        int a[] = new int[l];
        for(int i=0; i<l; i++)
            a[i] = sc.nextInt();
        Arrays.sort(a);
        int max = a[l-1];
        int moves = 0;
        boolean flag = true;
        for(int i=l-2; i>=0; i--) {
            int temp = max - a[i];
            max = a[i];
            if(temp % d == 0)
                moves += temp / d;
            else {
                flag = false;
                break;
            }
        }
        System.out.println(flag ? moves+1 : "-1");
    }
}


import java.io.*;
import java.util.*;

import static java.lang.Integer.*;
import static java.lang.Long.*;

public class B {
    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter pw = new PrintWriter(System.out);
        StringTokenizer st;
        st = new StringTokenizer(in.readLine());
        int n = parseInt(st.nextToken()), m = parseInt(st.nextToken()), d = parseInt(st.nextToken());
        boolean yes = true;
        int[] arr = new int[n * m];
        int ind = 0;
        int min = 100000;
        int max = -1;
        for (int i = 0; i < n; i++) {
            st = new StringTokenizer(in.readLine());
            for (int j = 0; j < m; j++) {
                int a = parseInt(st.nextToken());
                arr[ind] = a;
                min = Math.min(min, a);
                max = Math.max(max, a);
                if (a % d != 0) yes = false;
                ind++;
            }
        }
        int ans = solve(arr, n, yes, min, max, d);
        pw.println(ans);

        pw.close();
    }

    static int solve(int[] arr, int n, boolean isDivisble, int min, int max, int d) {
        if (!isDivisble) return -1;
        int left = min, right = max;
        while (left <= right) {
            int mid = (left + ((right - left) / 3));
            int ans1 = val(arr, n, mid + d);
            int ans2 = val(arr, n, mid - d);
            int ans = val(arr, n, mid);

            if (ans1 >= ans && ans <= ans2) {
                return ans;
            } else if (ans1 < ans && ans < ans2) {
                left = mid - d;
            } else {
                right = mid - d;
            }
        }
        return -1;
    }

    static int val(int[] arr, int n, int d) {
        int res = 0;
        for (int i = 0; i < n; i++) {
            res += Math.abs(arr[i] - d);
        }
        return res;
    }
}


import java.io.*;
import java.util.*;

import static java.lang.Integer.*;

public class B {
    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter pw = new PrintWriter(System.out);
        StringTokenizer st;
        st = new StringTokenizer(in.readLine());
        int n = parseInt(st.nextToken()), m = parseInt(st.nextToken()), d = parseInt(st.nextToken());
        int[] arr = new int[n * m];
        int ind = 0;
        for (int i = 0; i < n; i++) {
            st = new StringTokenizer(in.readLine());
            for (int j = 0; j < m; j++) {
                arr[ind] = parseInt(st.nextToken());
                if (ind != 0) {
                    if (arr[ind - 1] % d != arr[ind] % d) {
                        pw.println(-1);
                        pw.close();
                        return;
                    }
                }
                ind++;
            }
        }
        pw.println(solve(arr, n, m, d));
        pw.close();
    }

    static int solve(int[] arr, int n, int m, int d) {
        Arrays.sort(arr);
        int midVal = arr[((n * m) / 2)];
        int res = 0;
        for (int val : arr) {
            res += Math.abs(val - midVal);
        }
        return res / d;
    }
}


import java.io.*;
import java.util.*;

import static java.lang.Integer.*;
import static java.lang.Long.*;

public class B {
    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter pw = new PrintWriter(System.out);
        StringTokenizer st;
        st = new StringTokenizer(in.readLine());
        int n = parseInt(st.nextToken()), m = parseInt(st.nextToken()), d = parseInt(st.nextToken());
        boolean yes = true;
        int[] arr = new int[n * m];
        int ind = 0;
        int min = 100000;
        int max = -1;
        for (int i = 0; i < n; i++) {
            st = new StringTokenizer(in.readLine());
            for (int j = 0; j < m; j++) {
                int a = parseInt(st.nextToken());
                arr[ind] = a;
                min = Math.min(min, a);
                max = Math.max(max, a);
                if (a % d != 0) yes = false;
                ind++;
            }
        }
        int ans = solve(arr, n*m, yes, min, max, d) / 2;
        pw.println(ans);

        pw.close();
    }

    static int solve(int[] arr, int n, boolean isDivisble, int min, int max, int d) {
        if (!isDivisble) return -1;
        int left = min, right = max;
        while (left <= right) {
            int mid = (left + ((right - left) / 3));
            int ans1 = val(arr, n, mid + d);
            int ans2 = val(arr, n, mid - d);
            int ans = val(arr, n, mid);
            if (ans1 >= ans && ans <= ans2) {
                return ans;
            } else if (ans1 < ans && ans < ans2) {
                left = mid - d;
            } else {
                right = mid - d;
            }
        }
        return -1;
    }

    static int val(int[] arr, int n, int d) {
        int res = 0;
        for (int i = 0; i < n; i++) {
            res += Math.abs(arr[i] - d);
        }
        return res;
    }
}


import java.io.*;
import java.util.*;

import static java.lang.Integer.*;
import static java.lang.Long.*;

public class B {
    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter pw = new PrintWriter(System.out);
        StringTokenizer st;
        st = new StringTokenizer(in.readLine());
        int n = parseInt(st.nextToken()), m = parseInt(st.nextToken()), d = parseInt(st.nextToken());
        boolean yes = true;
        int[] arr = new int[n * m];
        int ind = 0;
        int min = 100000;
        int max = -1;
        for (int i = 0; i < n; i++) {
            st = new StringTokenizer(in.readLine());
            for (int j = 0; j < m; j++) {
                int a = parseInt(st.nextToken());
                arr[ind] = a;
                min = Math.min(min, a);
                max = Math.max(max, a);
                if (a % d != 0) yes = false;
                ind++;
            }
        }
        int ans = solve(arr, n * m, min, max, d);
        if (ans == 0) pw.println(-1);
        else pw.println((ans/d));

        pw.close();
    }

    static int solve(int[] arr, int n, int min, int max, int d) {
        int left = min, right = max;
        while (left <= right) {
            int mid = (left + ((right - left) / 3));
            int ans1 = val(arr, n, mid + d);
            int ans2 = val(arr, n, mid - d);
            int ans = val(arr, n, mid);
            if (ans1 >= ans && ans <= ans2) {
                return ans;
            } else if (ans1 < ans && ans < ans2) {
                left = mid - d;
            } else {
                right = mid - d;
            }
        }
        return -1;
    }

    static int val(int[] arr, int n, int d) {
        int res = 0;
        for (int i = 0; i < n; i++) {
            res += Math.abs(arr[i] - d);
        }
        return res;
    }
}


import java.io.*;
import java.util.*;

import static java.lang.Integer.*;
import static java.lang.Long.*;

public class B {
    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter pw = new PrintWriter(System.out);
        StringTokenizer st;
        st = new StringTokenizer(in.readLine());
        int n = parseInt(st.nextToken()), m = parseInt(st.nextToken()), d = parseInt(st.nextToken());
        boolean yes = true;
        int[] arr = new int[n * m];
        int ind = 0;
        int min = 100000;
        int max = -1;
        for (int i = 0; i < n; i++) {
            st = new StringTokenizer(in.readLine());
            for (int j = 0; j < m; j++) {
                int a = parseInt(st.nextToken());
                arr[ind] = a;
                min = Math.min(min, a);
                max = Math.max(max, a);
                if (a % d != 0) yes = false;
                ind++;
            }
        }
        int ans = solve(arr, n * m, yes, min, max, d);
        if (ans == -1) pw.println(-1);
        else pw.println((ans / 2));

        pw.close();
    }

    static int solve(int[] arr, int n, boolean isDivisble, int min, int max, int d) {
        if (!isDivisble) return -1;
        int left = min, right = max;
        while (left <= right) {
            int mid = (left + ((right - left) / 3));
            int ans1 = val(arr, n, mid + d);
            int ans2 = val(arr, n, mid - d);
            int ans = val(arr, n, mid);
            if (ans1 >= ans && ans <= ans2) {
                return ans;
            } else if (ans1 < ans && ans < ans2) {
                left = mid - d;
            } else {
                right = mid - d;
            }
        }
        return -1;
    }

    static int val(int[] arr, int n, int d) {
        int res = 0;
        for (int i = 0; i < n; i++) {
            res += Math.abs(arr[i] - d);
        }
        return res;
    }
}


import java.io.*;
import java.util.*;

import static java.lang.Integer.*;
import static java.lang.Long.*;

public class B {
    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter pw = new PrintWriter(System.out);
        StringTokenizer st;
        st = new StringTokenizer(in.readLine());
        int n = parseInt(st.nextToken()), m = parseInt(st.nextToken()), d = parseInt(st.nextToken());
        boolean yes = true;
        int[] arr = new int[n * m];
        int ind = 0;
        int min = 100000;
        int max = -1;
        for (int i = 0; i < n; i++) {
            st = new StringTokenizer(in.readLine());
            for (int j = 0; j < m; j++) {
                int a = parseInt(st.nextToken());
                arr[ind] = a;
                min = Math.min(min, a);
                max = Math.max(max, a);
                if (a % d != 0) yes = false;
                ind++;
            }
        }
        int ans = solve(arr, n * m, yes, min, max, d);
        if (ans == -1) pw.println(-1);
        else pw.println((ans / d));

        pw.close();
    }

    static int solve(int[] arr, int n, boolean isDivisble, int min, int max, int d) {
        if (!isDivisble) return -1;
        int left = min, right = max;
        while (left <= right) {
            int mid = (left + ((right - left) / 3));
            int ans1 = val(arr, n, mid + d);
            int ans2 = val(arr, n, mid - d);
            int ans = val(arr, n, mid);
            if (ans1 >= ans && ans <= ans2) {
                return ans;
            } else if (ans1 < ans && ans < ans2) {
                left = mid - d;
            } else {
                right = mid - d;
            }
        }
        return -1;
    }

    static int val(int[] arr, int n, int d) {
        int res = 0;
        for (int i = 0; i < n; i++) {
            res += Math.abs(arr[i] - d);
        }
        return res;
    }
}


import java.io.*;
import java.util.*;

import static java.lang.Integer.*;
import static java.lang.Long.*;

public class B {
    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter pw = new PrintWriter(System.out);
        StringTokenizer st;
        st = new StringTokenizer(in.readLine());
        int n = parseInt(st.nextToken()), m = parseInt(st.nextToken()), d = parseInt(st.nextToken());
        boolean yes = true;
        int[] arr = new int[n * m];
        int ind = 0;
        int min = 100000;
        int max = -1;
        for (int i = 0; i < n; i++) {
            st = new StringTokenizer(in.readLine());
            for (int j = 0; j < m; j++) {
                int a = parseInt(st.nextToken());
                arr[ind] = a;
                min = Math.min(min, a);
                max = Math.max(max, a);
                if (a % d != 0) yes = false;
                ind++;
            }
        }
        int ans = solve(arr, n * m, min, max, d);
        if (ans % d != 0) pw.println(-1);
        else pw.println((ans / d));

        pw.close();
    }

    static int solve(int[] arr, int n, int min, int max, int d) {
        int left = min, right = max;
        while (left <= right) {
            int mid = (left + ((right - left) / 3));
            int ans1 = val(arr, n, mid + d);
            int ans2 = val(arr, n, mid - d);
            int ans = val(arr, n, mid);
            if (ans1 >= ans && ans <= ans2) {
                return ans;
            } else if (ans1 < ans && ans < ans2) {
                left = mid - d;
            } else {
                right = mid - d;
            }
        }
        return -1;
    }

    static int val(int[] arr, int n, int d) {
        int res = 0;
        for (int i = 0; i < n; i++) {
            res += Math.abs(arr[i] - d);
        }
        return res;
    }
}


import java.io.*;
import java.util.*;

import static java.lang.Integer.*;
import static java.lang.Long.*;

public class B {
    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter pw = new PrintWriter(System.out);
        StringTokenizer st;
        st = new StringTokenizer(in.readLine());
        int n = parseInt(st.nextToken()), m = parseInt(st.nextToken()), d = parseInt(st.nextToken());
        boolean yes = true;
        int[] arr = new int[n * m];
        int ind = 0;
        int min = 100000;
        int max = -1;
        for (int i = 0; i < n; i++) {
            st = new StringTokenizer(in.readLine());
            for (int j = 0; j < m; j++) {
                int a = parseInt(st.nextToken());
                arr[ind] = a;
                min = Math.min(min, a);
                max = Math.max(max, a);
                if (a % d != 0) yes = false;
                ind++;
            }
        }
        int ans = solve(arr, n * m, min, max, d);
        if ((ans / d) == 0) pw.println(-1);
        else pw.println((ans/d));

        pw.close();
    }

    static int solve(int[] arr, int n, int min, int max, int d) {
        int left = min, right = max;
        while (left <= right) {
            int mid = (left + ((right - left) / 3));
            int ans1 = val(arr, n, mid + d);
            int ans2 = val(arr, n, mid - d);
            int ans = val(arr, n, mid);
            if (ans1 >= ans && ans <= ans2) {
                return ans;
            } else if (ans1 < ans && ans < ans2) {
                left = mid - d;
            } else {
                right = mid - d;
            }
        }
        return -1;
    }

    static int val(int[] arr, int n, int d) {
        int res = 0;
        for (int i = 0; i < n; i++) {
            res += Math.abs(arr[i] - d);
        }
        return res;
    }
}


import java.io.*;
import java.util.*;

import static java.lang.Integer.*;
import static java.lang.Long.*;

public class B {
    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter pw = new PrintWriter(System.out);
        StringTokenizer st;
        st = new StringTokenizer(in.readLine());
        int n = parseInt(st.nextToken()), m = parseInt(st.nextToken()), d = parseInt(st.nextToken());
        boolean yes = true;
        int[] arr = new int[n * m];
        int ind = 0;
        int min = 100000;
        int max = -1;
        for (int i = 0; i < n; i++) {
            st = new StringTokenizer(in.readLine());
            for (int j = 0; j < m; j++) {
                int a = parseInt(st.nextToken());
                arr[ind] = a;
                min = Math.min(min, a);
                max = Math.max(max, a);
                if (a % d != 0) yes = false;
                ind++;
            }
        }
        int ans = solve(arr, n * m, min, max, d);
        if (ans % d == 0) pw.println((ans/d));
        else pw.println(-1);
        pw.close();
    }

    static int solve(int[] arr, int n, int min, int max, int d) {
        int left = min, right = max;
        while (left <= right) {
            int mid = (left + ((right - left) / 3));
            int ans1 = val(arr, n, mid + 1);
            int ans2 = val(arr, n, mid - 1);
            int ans = val(arr, n, mid);
            if (ans1 >= ans && ans <= ans2) {
                return ans;
            } else if (ans1 < ans && ans < ans2) {
                left = mid - d;
            } else {
                right = mid - d;
            }
        }
        return -1;
    }

    static int val(int[] arr, int n, int d) {
        int res = 0;
        for (int i = 0; i < n; i++) {
            res += Math.abs(arr[i] - d);
        }
        return res;
    }
}


import java.io.*;
import java.util.*;

import static java.lang.Integer.*;
import static java.lang.Long.*;

public class B {
    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter pw = new PrintWriter(System.out);
        StringTokenizer st;
        st = new StringTokenizer(in.readLine());
        int n = parseInt(st.nextToken()), m = parseInt(st.nextToken()), d = parseInt(st.nextToken());
        boolean yes = true;
        int[] arr = new int[n * m];
        int ind = 0;
        int min = 100000;
        int max = -1;
        for (int i = 0; i < n; i++) {
            st = new StringTokenizer(in.readLine());
            for (int j = 0; j < m; j++) {
                int a = parseInt(st.nextToken());
                arr[ind] = a;
                min = Math.min(min, a);
                max = Math.max(max, a);
                if (a % d != 0) yes = false;
                ind++;
            }
        }
        int ans = solve(arr, n * m, min, max, d);
        if (ans == 0) pw.println(-1);
        else pw.println((ans / d));

        pw.close();
    }

    static int solve(int[] arr, int n, int min, int max, int d) {
        int left = min, right = max;
        while (left <= right) {
            int mid = (left + ((right - left) / 3));
            int ans1 = val(arr, n, mid + d);
            int ans2 = val(arr, n, mid - d);
            int ans = val(arr, n, mid);
            if (ans1 >= ans && ans <= ans2) {
                return ans;
            } else if (ans1 < ans && ans < ans2) {
                left = mid - d;
            } else {
                right = mid - d;
            }
        }
        return -1;
    }

    static int val(int[] arr, int n, int d) {
        int res = 0;
        for (int i = 0; i < n; i++) {
            res += Math.abs(arr[i] - d);
        }
        return res;
    }
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Arrays;

public class PoloThePenguinAndMatrix{
public static void main(String[] args) throws IOException {
	BufferedReader br=  new BufferedReader(new InputStreamReader(System.in));
	PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out));
	String [] sp = br.readLine().split(" ");
	int n = Integer.parseInt(sp[0]);
	int m = Integer.parseInt(sp[1]);
	int d = Integer.parseInt(sp[2]);
	int [] num = new int[n*m];
	for(int i=0;i<n;i++){
		sp = br.readLine().split(" " );
		for(int j=0;j<m ;j++)
		{
			num[i*m+j]= Integer.parseInt(sp[j]);
		}
	}
	Arrays.sort(num);
	int offset = 0;
	int countUnique = 1;
	for(int i=0;i<n-1;i++)
	{
		if(num[i]!=num[i+1])
			countUnique++;
	}
	for(int i=0,uniqueSoFar= 1;i<n;i++)
	{
		if(num[i]==num[i+1] && uniqueSoFar<countUnique/2)
			offset++;
		else if(num[i]==num[i+1])
			offset--;
	}
	int median = num[num.length/2+offset];
	boolean ok = true;
	int moves = 0;
	for(int i=0;i<num.length;i++)
	{
		if((int)(Math.abs(num[i]-median)%d)!=0)
		{
			ok = false;
			break;
		}else {
			moves += ((int)Math.abs(num[i]-median))/d;
		}
	}
	if(ok)
		System.out.println(moves);
	else
		System.out.println("-1");

}
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Arrays;

public class PoloThePenguinAndMatrix{
public static void main(String[] args) throws IOException {
	BufferedReader br=  new BufferedReader(new InputStreamReader(System.in));
	PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out));
	String [] sp = br.readLine().split(" ");
	int n = Integer.parseInt(sp[0]);
	int m = Integer.parseInt(sp[1]);
	int d = Integer.parseInt(sp[2]);
	int [] num = new int[n*m];
	for(int i=0;i<n;i++){
		sp = br.readLine().split(" " );
		for(int j=0;j<m ;j++)
		{
			num[n*i+j]= Integer.parseInt(sp[j]);
		}
	}
	Arrays.sort(num);
	int offset = 0;
	int countUnique = 1;
	for(int i=0;i<n-1;i++)
	{
		if(num[i]!=num[i+1])
			countUnique++;
	}
	for(int i=0,uniqueSoFar= 1;i<n;i++)
	{
		if(num[i]==num[i+1] && uniqueSoFar<countUnique/2)
			offset++;
		else if(num[i]==num[i+1])
			offset--;
	}
	int median = num[num.length/2+offset];
	boolean ok = true;
	int moves = 0;
	for(int i=0;i<num.length;i++)
	{
		if((int)(Math.abs(num[i]-median)%d)!=0)
		{
			ok = false;
			break;
		}else {
			moves += ((int)Math.abs(num[i]-median))/d;
		}
	}
	if(ok)
		System.out.println(moves);
	else
		System.out.println("-1");

}
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Arrays;

public class PoloThePenguinAndMatrix{
public static void main(String[] args) throws IOException {
	BufferedReader br=  new BufferedReader(new InputStreamReader(System.in));
	PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out));
	String [] sp = br.readLine().split(" ");
	int n = Integer.parseInt(sp[0]);
	int m = Integer.parseInt(sp[1]);
	int d = Integer.parseInt(sp[2]);
	int [] num = new int[n*m];
	for(int i=0;i<n;i++){
		sp = br.readLine().split(" " );
		for(int j=0;j<m ;j++)
		{
			num[i*m+j]= Integer.parseInt(sp[j]);
		}
	}
	Arrays.sort(num);

	int median = num[n*m/2];

	boolean ok = true;
	int moves = 0;
	for(int i=0;i<num.length;i++)
	{
		if((int)(Math.abs(num[i]-median)%d)!=0)
		{
			ok = false;
			break;
		}else {
			moves += ((int)Math.abs(num[i]-median))/d;
		}
	}
	if(ok)
		System.out.println(moves);
	else
		System.out.println("-1");

}
}


import java.util.HashSet;
import java.util.*;
import java.util.Scanner;
import java.util.Set;
import java.util.ArrayList;
import java.util.Collections;
import java.text.DecimalFormat;
import java.lang.Math;
public class Lo {
    public static void main(String[] args){
      Scanner sc = new Scanner(System.in);
      int n = sc.nextInt();
      int m = sc.nextInt();
      int d = sc.nextInt();
      int flag = 0;
      ArrayList<Integer> A = new ArrayList<Integer>();
      int[][] a = new int[n][m];
      for(int i = 0; i < n; i++){
          for(int j = 0; j < m; j++){
              A.add(sc.nextInt());
          }
      }
      Collections.sort(A);
      int count = 0;
      int p = A.get((A.size())/2);
      int k = p%d;
      for(int i = 0; i < A.size(); i++){
          if(A.get(i)%d != k){
              flag = 1;
              break;
          }
          else{
              if(Math.abs(A.get(i)-p)%d==0){
                  count += Math.abs(A.get(i)-p)/d;
              }
              else{
                  flag = 1;
              }
          }
      }
      if(flag==1){
          System.out.println(-1);
      }
      else{
          System.out.println(count);
      }
    }
}


import java.util.HashSet;
import java.util.*;
import java.util.Scanner;
import java.util.Set;
import java.util.ArrayList;
import java.util.Collections;
import java.text.DecimalFormat;
import java.lang.Math;
public class Lo {
    public static void main(String[] args){
      Scanner sc = new Scanner(System.in);
      int n = sc.nextInt();
      int m = sc.nextInt();
      int d = sc.nextInt();
      int min = -1;
      int max = -1;
      int flag = 0;
      int[][] a = new int[n][m];
      for(int i = 0; i < n; i++){
          for(int j = 0; j < m; j++){
              int x = sc.nextInt();
              if(x%d != 0){
                  flag = 1;
              }
              if(x < min || min == -1){
                  min = x;
              }
              if(x > max || max == -1){
                  max = x;
              }
          }
      }
      if(flag == 1){
          System.out.println(-1);
      }
      else if(min != 0){
          System.out.println(max/min);
      }
      else if(min == 0){
          System.out.println(max/d);
      }
    }
}


import java.util.*;
import java.lang.*;
import java.math.*;
import java.io.*;
import java.util.HashSet;
import java.util.Arrays;
import java.util.Scanner;
import java.util.Set;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.text.DecimalFormat;
import java.lang.Math;
import java.util.Iterator;
import java.util.TreeSet;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.*;
public class D1343{
	public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out));
	static long MOD = (long)(1e9+7);
	static FastReader sc = new FastReader();
	static int pInf = Integer.MAX_VALUE;
	static int nInf = Integer.MIN_VALUE;
	public static void main(String[] args){
		int test = 1;
		while(test-->0){
		    int n = sc.nextInt();
		    int m = sc.nextInt();
		    int d = sc.nextInt();
		    ArrayList<Integer> A = new ArrayList<Integer>();
		    for(int i = 0; i < n*m; i++){
		        A.add(sc.nextInt());
		    }
		    int count = 0;
		    boolean flag = false;
		    Collections.sort(A);
		    int k = A.get((n*m)/2)%d;
		    for(int i = 0; i < A.size(); i++){
		        if((A.get(i)%d)!=k){
		            flag = true;
		            break;
		        }
		        else{
		            if(Math.abs(A.get(i)-A.get(A.size()/2))%d==0){
		                count += Math.abs(A.get(i)-A.get(A.size()/2))/d;
		            }
		            else{
		                flag = true;
		            }
		        }
		    }
		    if(flag){
		        out.println(-1);
		    }
		    else{
		        out.println(count);
		    }
		}
		out.close();
	}
	public static long mul(long a, long b){
	    return ((a%MOD)*(b%MOD))%MOD;
	}
	public static long add(long a, long b){
	    return ((a%MOD)+(b%MOD))%MOD;
	}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Integer.lowestOneBit(i)   Equals k where k is the position of the first one in the binary
//Integer.highestOneBit(i)  Equals k where k is the position of the last one in the binary
//Integer.bitCount(i)       returns the number of one-bits
//Collections.sort(A,(p1,p2)->(int)(p2.x-p1.x)) To sort ArrayList in descending order wrt values of x.
//            Arrays.parallelSort(a,new Comparator<TPair>() {
//      		public int compare(TPair a,TPair b) {
//        			if(a.y==b.y) return a.x-b.x;
//        			return b.y-a.y;
//        		}
//        	});
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//PrimeFactors
    public static ArrayList<Long> primeFactors(long n) {
        ArrayList<Long> arr = new ArrayList<>();
        if (n % 2 == 0)
            arr.add((long) 2);
        while (n % 2 == 0)
            n /= 2;
        for (long i = 3; i <= Math.sqrt(n); i += 2) {
            int flag = 0;
            while (n % i == 0) {
                n /= i;
                flag = 1;
            }
            if (flag == 1)
                arr.add(i);
        }
        if (n > 2)
            arr.add(n);
        return arr;
    }
//Pair Class
	static class Pair implements Comparable<Pair>{
		int x;
		int y;
		public Pair(int x, int y) {
			this.x = x;
			this.y = y;
		}
		@Override
		public int compareTo(Pair o) {
			// TODO Auto-generated method stub
			if(this.y==o.y){
			    return (this.x-o.x);
			}
			return (this.y-o.y);
		}
	}
	static class TPair{
		int x;
		int y;
		int z;
		public TPair(int x, int y, int z) {
			this.x = x;
			this.y = y;
			this.z = z;
		}
	}
//Merge Sort
	static void merge(long arr[], int l, int m, int r)
    {
        // Find sizes of two subarrays to be merged
        int n1 = m - l + 1;
        int n2 = r - m;

        /* Create temp arrays */
        long L[] = new long [n1];
        long R[] = new long [n2];

        /*Copy data to temp arrays*/
        for (int i=0; i<n1; ++i)
            L[i] = arr[l + i];
        for (int j=0; j<n2; ++j)
            R[j] = arr[m + 1+ j];

        /* Merge the temp arrays */

        // Initial indexes of first and second subarrays
        int i = 0, j = 0;

        // Initial index of merged subarry array
        int k = l;
        while (i < n1 && j < n2)
        {
            if (L[i] <= R[j])
            {
                arr[k] = L[i];
                i++;
            }
            else
            {
                arr[k] = R[j];
                j++;
            }
            k++;
        }

        /* Copy remaining elements of L[] if any */
        while (i < n1)
        {
            arr[k] = L[i];
            i++;
            k++;
        }

        /* Copy remaining elements of R[] if any */
        while (j < n2)
        {
            arr[k] = R[j];
            j++;
            k++;
        }
    }

    // Main function that sorts arr[l..r] using
    // merge()
    static void sort(long arr[], int l, int r)
    {
        if (l < r)
        {
            // Find the middle point
            int m = (l+r)/2;

            // Sort first and second halves
            sort(arr, l, m);
            sort(arr , m+1, r);

            // Merge the sorted halves
            merge(arr, l, m, r);
        }
    }
//Brian Kernighan’s Algorithm
    static long countSetBits(long n){
        if(n==0) return 0;
        return 1+countSetBits(n&(n-1));
    }
//Factorial
    static long factorial(long n){
        if(n==1) return 1;
        if(n==2) return 2;
        if(n==3) return 6;
        return n*factorial(n-1);
    }
//Euclidean Algorithm
    static long gcd(long A,long B){
        if(B==0) return A;
        return gcd(B,A%B);
    }
//Modular Exponentiation
    static long fastExpo(long x,long n){
        if(n==0) return 1;
        if((n&1)==0) return fastExpo((x*x)%MOD,n/2)%MOD;
        return ((x%MOD)*fastExpo((x*x)%MOD,(n-1)/2))%MOD;
    }
//AKS Algorithm
    static boolean isPrime(long n){
        if(n<=1) return false;
        if(n<=3) return true;
        if(n%2==0 || n%3==0) return false;
        for(int i=5;i*i<=n;i+=6)
            if(n%i==0 || n%(i+2)==0) return false;
        return true;
    }
//Reverse an array
    static <T> void reverse(T arr[],int l,int r){
    	Collections.reverse(Arrays.asList(arr).subList(l, r));
    }
//Sieve of eratosthenes
    static int[] findPrimes(int n){
        boolean isPrime[]=new boolean[n+1];
        ArrayList<Integer> a=new ArrayList<>();
        int result[];
        Arrays.fill(isPrime,true);
        isPrime[0]=false;
        isPrime[1]=false;
        for(int i=2;i*i<=n;++i){
            if(isPrime[i]==true){
                for(int j=i*i;j<=n;j+=i) isPrime[j]=false;
            }
        }
        for(int i=0;i<=n;i++) if(isPrime[i]==true) a.add(i);
        result=new int[a.size()];
        for(int i=0;i<a.size();i++) result[i]=a.get(i);
        return result;

    }
//Euler Totent function
    static long countCoprimes(long n){
        ArrayList<Long> prime_factors=new ArrayList<>();
        long x=n,flag=0;
        while(x%2==0){
            if(flag==0) prime_factors.add(2L);
            flag=1;
            x/=2;
        }
        for(long i=3;i*i<=x;i+=2){
            flag=0;
            while(x%i==0){
                if(flag==0) prime_factors.add(i);
                flag=1;
                x/=i;
            }
        }
        if(x>2) prime_factors.add(x);
        double ans=(double)n;
        for(Long p:prime_factors){
            ans*=(1.0-(Double)1.0/p);
        }
        return (long)ans;
    }
	static long modulo = (long)1e9+7;
	public static long modinv(long x){
	    return modpow(x, modulo-2);
	}
	public static long modpow(long a, long b){
	    if(b==0){
	        return 1;
	    }
	    long x = modpow(a, b/2);
	    x = (x*x)%modulo;
	    if(b%2==1){
	        return (x*a)%modulo;
	    }
	    return x;
	}
	public static class FastReader {
		BufferedReader br;
		StringTokenizer st;
		//it reads the data about the specified point and divide the data about it ,it is quite fast
		//than using direct

		public FastReader() {
			br = new BufferedReader(new InputStreamReader(System.in));
		}

		String next() {
			while (st == null || !st.hasMoreTokens()) {
				try {
					st = new StringTokenizer(br.readLine());
				} catch (Exception r) {
					r.printStackTrace();
				}
			}
			return st.nextToken();
		}

		int nextInt() {
			return Integer.parseInt(next());//converts string to integer
		}

		double nextDouble() {
			return Double.parseDouble(next());
		}

		long nextLong() {
			return Long.parseLong(next());
		}

		String nextLine() {
			String str = "";
			try {
				str = br.readLine();
			} catch (Exception r) {
				r.printStackTrace();
			}
			return str;
		}
	}
}


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
import java.util.TreeSet;

public class CF289B {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		BufferedReader bu = new BufferedReader(new InputStreamReader(System.in));
		PrintWriter out = new PrintWriter(System.out);

		int n = sc.nextInt();
		int m = sc.nextInt();
		int d= sc.nextInt();
		int[][] arr = new int[n][m];
		TreeSet<Integer> set = new TreeSet<>();
		ArrayList<Integer> list = new ArrayList<>();
		int pos = 0;
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < m; j++) {
				arr[i][j] = sc.nextInt();
				if (!set.contains(arr[i][j])) {
					list.add(arr[i][j]);
					set.add(arr[i][j]);
				}
			}
		}

		int mid = 0;
		Collections.sort(list);

		mid = list.get(list.size()/2);

		int maxmoves = 0;
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < m; j++) {
				int temp = arr[i][j];

				if (Math.abs(temp-mid)%d==0) {
					maxmoves += Math.abs(temp-mid)/d;
				}else {
					System.out.println(-1);
					return;
				}
			}
		}

		System.out.println(maxmoves);

		out.close();
	}

}


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
import java.util.TreeSet;

public class CF289B {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		BufferedReader bu = new BufferedReader(new InputStreamReader(System.in));
		PrintWriter out = new PrintWriter(System.out);

		int n = sc.nextInt();
		int m = sc.nextInt();
		int d= sc.nextInt();
		int[][] arr = new int[n][m];
		TreeSet<Integer> set = new TreeSet<>();
		ArrayList<Integer> list = new ArrayList<>();
		int pos = 0;
		int avg = 0;
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < m; j++) {
				arr[i][j] = sc.nextInt();
				if (!set.contains(arr[i][j])) {
					list.add(arr[i][j]);
					set.add(arr[i][j]);
				}
				avg += arr[i][j];
			}
		}
		avg /= (n*m);
		int mid = 0;
		Collections.sort(list);

		int mindis = Integer.MAX_VALUE;
		int num = arr[0][0];

		for (int i = 0; i < n; i++) {
			for (int j = 0; j < m; j++) {
//				System.out.println(arr[i][j] + " " + (arr[i][j]-avg));
				if (Math.abs(arr[i][j]-avg) < mindis) {
					mindis = Math.abs(arr[i][j]-avg);
					num = arr[i][j];
				}
			}
		}

		int moves = 0;
//		System.out.println(avg + " " + num);
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < m; j++) {
				if (Math.abs(arr[i][j]-num)%d == 0) {
					moves += (Math.abs(arr[i][j]-num))/d;
				}else {
					System.out.println(-1);
					return;
				}
			}
		}
		System.out.println(moves);
		out.close();
	}

}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;
import java.util.TreeSet;

public class CF289B {

	public static void main(String[] args) throws IOException {
//		Scanner sc = new Scanner(System.in);
		BufferedReader bu = new BufferedReader(new InputStreamReader(System.in));
		PrintWriter out = new PrintWriter(System.out);

		String[] in = bu.readLine().split(" ");
		int n = Integer.parseInt(in[0]);
		int m = Integer.parseInt(in[1]);
		int d= Integer.parseInt(in[2]);

		int[] arr = new int[n*m];

		int pos = 0;
		for (int i = 0; i < n; i++) {
			in = bu.readLine().split(" ");
			for (int j =0; j < m; j++) {
				arr[pos] = Integer.parseInt(in[j]);
				pos++;
			}
		}
//		System.out.println(Arrays.toString(arr));
		int minmoves = Integer.MAX_VALUE;
		Arrays.sort(arr);
		outer : for (int i = 0; i < n*m-1; i++) {
			int localm = 0;
			for (int j = 0; j < n*m; j++) {
				if (i == j) continue;
//				System.out.println(arr[i] +  " " + arr[j] + " "  + (Math.abs(arr[i]-arr[j])%d));
				if (Math.abs(arr[i]-arr[j])%d == 0) {
					localm += (Math.abs(arr[i]-arr[j]))/d;
				}else {
					continue outer;
				}
			}
			minmoves = Math.min(minmoves, localm);
		}
		out.println(minmoves == Integer.MAX_VALUE ? -1 : minmoves);
		out.close();
	}

}


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
import java.util.TreeSet;

public class CF289B {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		BufferedReader bu = new BufferedReader(new InputStreamReader(System.in));
		PrintWriter out = new PrintWriter(System.out);

		int n = sc.nextInt();
		int m = sc.nextInt();
		int d= sc.nextInt();
		int[][] arr = new int[n][m];
		TreeSet<Integer> set = new TreeSet<>();
		ArrayList<Integer> list = new ArrayList<>();
		int pos = 0;
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < m; j++) {
				arr[i][j] = sc.nextInt();
				if (!set.contains(arr[i][j])) {
					list.add(arr[i][j]);
					set.add(arr[i][j]);
				}
			}
		}

		int mid = 0;
		Collections.sort(list);

		mid = list.get(list.size()/2);
		int mid2 = list.get(Math.max(0,list.size()/2-1));
		int maxmoves = 0;
		int mm2 = 0;
		boolean bad1 = false, bad2 = false;
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < m; j++) {
				int temp = arr[i][j];

				if (Math.abs(temp-mid)%d==0) {
					maxmoves += Math.abs(temp-mid)/d;
				}else {
					bad1 = true;
				}

				if (Math.abs(temp-mid2)%d==0) {
					mm2 += Math.abs(temp-mid2)/d;
				}else {
					bad2 = true;
				}
			}
		}

		if (bad2 && bad1) {
			System.out.println(-1);
		}else if (bad1) {
			System.out.println(mm2);
		}else if (bad2) {
			System.out.println(maxmoves);
		}else {
			System.out.println(Math.min(mm2, maxmoves));
		}

		out.close();
	}

}


#include <iostream>
#include <vector>
#include <queue>
using namespace std;

int min1 = 100001, visited[100001] = { 0 }, n;

void brute(vector<long long> arr[100001], vector<long long> arr2[61], int node, int num, int exep) {
	visited[node] = num;
	//cout << node << " " << num << endl;
	for (int i = 0; i < arr[node].size(); i++) {
		int temp = arr[node][i];
		if (temp == exep) continue;
		for (int j = 0; j < arr2[temp].size(); j++) {
			int temp2 = arr2[temp][j];
			//cout << node << " " << temp2 << " " << visited[node] << " " << visited[temp2] << endl;
			if (!visited[temp2]) {
				brute(arr, arr2, temp2, num + 1, temp);
			}
			if (visited[temp2] && num>=3) {
				//cout << "check" << endl;
				int temp3 = num - visited[temp2] + 1;
				if (temp3 >= 3) min1 = min1 > temp3 ? temp3 : min1;
			}
		}
	}
}

int main()
{
	queue<int> q;
	long long arr[100001];
	vector<long long> arr2[100001], arr3[61];
	cin >> n;
	for (int i = 0; i < n; i++) {
		cin >> arr[i];
		long long m = 1;
		for (int j = 1; j <= 60; j++) {
			if ((arr[i] & m)) {
				arr2[i].push_back(j);
				arr3[j].push_back(i);
			}
			m <<= 1;
		}
	}
	for (int i = 0; i < n; i++) {
		if (!visited[i]) brute(arr2, arr3, i, 1 ,0);
	}
	if (min1 == 100001) cout << -1;
	else cout << min1;
    return 0;
}


#include <iostream>
#include <vector>
using namespace std;

int min1 = 100001, visited[100001] = { 0 }, n, chk=0;

void brute(vector<long long> arr[100001], int node, int num) {
	visited[node] = num;
	//cout << node << " " << num << endl;
	for (int i = 0; i < arr[node].size(); i++) {
		//cout << node << " test " << arr[node][i] << endl;
		int temp = arr[node][i];
		if (!visited[temp]) {
			brute(arr, arr[node][i], num + 1);
		}
		else if (num - visited[temp] + 1 >= 3) {
			min1 = min1 > num - visited[temp] + 1 ? num - visited[temp] + 1 : min1;
		}
	}
}

int main()
{
	ios::sync_with_stdio(0);
	cin.tie(NULL);
	long long arr[100001];
	vector<long long> arr2[100001], arr3[61];
	cin >> n;
	for (int i = 0; i < n; i++) {
		cin >> arr[i];
		long long m = 1;
		for (int j = 1; j <= 60; j++) {
			if ((arr[i] & m)) {
				arr3[j].push_back(i);
			}
			m <<= 1;
		}
	}
	for (int i = 1; i <= 60; i++) {
		if (arr3[i].size() >= 3) {
			chk = 1;
			break;
		}
		for (int j = 0; j < arr3[i].size(); j++) {
			for (int k = j + 1; k<arr3[i].size(); k++) {
				arr2[arr3[i][j]].push_back(arr3[i][k]);
				arr2[arr3[i][k]].push_back(arr3[i][j]);
			}
		}
	}
	for (int i = 0; i < n; i++) {
		if (!visited[i]) {
			visited[i] = 1;
			for (int j = 0; j < arr2[i].size(); j++) {
				brute(arr2, arr2[i][j], 2);
			}
		}
	}
	if (min1 == 100001) cout << -1;
	else cout << min1;
    return 0;
}


#include <iostream>
#include <vector>
#include <queue>
using namespace std;

int main()
{
	int n, visited[100001] = { 0 }, min=100001;
	queue<int> q;
	long long arr[100001];
	vector<long long> arr2[100001], arr3[61];
	cin >> n;
	for (int i = 0; i < n; i++) {
		cin >> arr[i];
		int m = 1;
		for (int j = 1; j <= 60; j++) {
			if ((arr[i] & m)) {
				arr2[i].push_back(j);
				arr3[j].push_back(i);
			}
			m <<= 1;
		}
	}
	for (int i = 0; i < n; i++) {
		int size = 1;
		if (!visited[i]) {
			int visit[61] = { 0 };
			q.push(i);
			visited[i] = size++;
			while (!q.empty()) {
				int node = q.front();
				q.pop();
				for (int j = 0; j < arr2[node].size(); j++) {
					int temp = arr2[node][j];
					visit[temp] = 1;
					for (int k = 0; k < arr3[temp].size(); k++) {
						if (arr3[temp][k] == node) continue;
						if (!visited[arr3[temp][k]]) {
							q.push(arr3[temp][k]);
							visited[arr3[temp][k]] = size;
						}
						else if (visited[arr3[temp][k]] + visited[node] > 3) {
							min = min > visited[arr3[temp][k]] + visited[node]-1 ? visited[arr3[temp][k]] + visited[node]-1 : min;
						}
					}
				}
				size++;
			}
		}
	}
	if (min == 100001) cout << -1;
	else cout << min;
    return 0;
}


#include <iostream>
#include <vector>
#include <queue>
using namespace std;

int min1 = 100001, visited[100001] = { 0 }, n;

void brute(vector<long long> arr[100001], vector<long long> arr2[61], int node, int num) {
	//cout << node << " " << num << endl;
	visited[node] = num;
	for (int i = 0; i < arr[node].size(); i++) {
		for (int j = 0; j < arr2[arr[node][i]].size(); j++) {
			int temp = arr2[arr[node][i]][j], temp2 = num-visited[temp]+1;
			if (!visited[temp]) {
				brute(arr, arr2, temp, num + 1);
			}
			else if(temp2 >=3){
				min1 = min1 > temp2 ? temp2 : min1;
			}
		}
	}
}

int main()
{
	queue<int> q;
	long long arr[100001];
	vector<long long> arr2[100001], arr3[61];
	cin >> n;
	for (int i = 0; i < n; i++) {
		cin >> arr[i];
		long long m = 1;
		for (int j = 1; j <= 60; j++) {
			if ((arr[i] & m)) {
				arr2[i].push_back(j);
				arr3[j].push_back(i);
			}
			m <<= 1;
		}
	}
	for (int i = 0; i < n; i++) {
		visited[i] = 1;
		for (int j = 0; j < arr2[i].size(); j++) {
			for (int k = 0; k < arr3[arr2[i][j]].size(); k++) {
				brute(arr2, arr3, arr3[arr2[i][j]][k], 2);
			}
		}
	}
	if (min1 == 100001) cout << -1;
	else cout << min1;
    return 0;
}


#include <iostream>
#include <vector>
#include <queue>
using namespace std;

int main()
{
	int n, visited[100001] = { 0 }, min=100001;
	queue<int> q;
	long long arr[100001];
	vector<long long> arr2[100001], arr3[61];
	cin >> n;
	for (int i = 0; i < n; i++) {
		cin >> arr[i];
		int m = 1;
		for (int j = 1; j <= 60; j++) {
			if ((arr[i] & m)) {
				arr2[i].push_back(j);
				arr3[j].push_back(i);
			}
			m <<= 1;
		}
	}
	for (int i = 1; i <= 60; i++) {
		if (arr3[i].size() >= 3) min = min > arr3[i].size() ? arr3[i].size() : min;
	}
	for (int i = 0; i < n; i++) {
		int size = 1;
		if (!visited[i]) {
			int visit[61] = { 0 };
			q.push(i);
			visited[i] = size++;
			while (!q.empty()) {
				int node = q.front();
				q.pop();
				for (int j = 0; j < arr2[node].size(); j++) {
					int temp = arr2[node][j];
					visit[temp] = 1;
					for (int k = 0; k < arr3[temp].size(); k++) {
						if (arr3[temp][k] == node) continue;
						if (!visited[arr3[temp][k]]) {
							q.push(arr3[temp][k]);
							visited[arr3[temp][k]] = size;
						}
						else if (visited[arr3[temp][k]] + visited[node] > 3) {
							min = min > visited[arr3[temp][k]] + visited[node]-1 ? visited[arr3[temp][k]] + visited[node]-1 : min;
						}
					}
				}
				size++;
			}
		}
	}
	if (min == 100001) cout << -1;
	else cout << min;
    return 0;
}


#include <iostream>
#include <vector>
#include <queue>
using namespace std;

int main()
{
	int n, visited[100001] = { 0 }, min=100001;
	queue<int> q;
	long long arr[100001];
	vector<long long> arr2[100001], arr3[61];
	cin >> n;
	for (int i = 0; i < n; i++) {
		cin >> arr[i];
		int m = 1;
		for (int j = 1; j <= 60; j++) {
			if ((arr[i] & m)) {
				arr2[i].push_back(j);
				arr3[j].push_back(i);
			}
			m <<= 1;
		}
	}
	for (int i = 0; i < n; i++) {
		int size = 1;
		if (!visited[i]) {
			int visit[61] = { 0 };
			q.push(i);
			visited[i] = size++;
			while (!q.empty()) {
				int node = q.front();
				q.pop();
				for (int j = 0; j < arr2[node].size(); j++) {
					int temp = arr2[node][j];
					//cout << "temp " << temp << endl;
					visit[temp] = 1;
					for (int k = 0; k < arr3[temp].size(); k++) {
						//cout << arr3[temp][k] << " ";
						if (arr3[temp][k] == node) continue;
						if (!visited[arr3[temp][k]]) {
							q.push(arr3[temp][k]);
							visited[arr3[temp][k]] = size;
						}
						else if (visited[arr3[temp][k]] + visited[node] > 3) {
							min = min > visited[arr3[temp][k]] + visited[node]-1 ? visited[arr3[temp][k]] + visited[node]-1 : min;
							cout << min << endl;
						}
					}
				}
				size++;
			}
		}
	}
	if (min == 100001) cout << -1;
	else cout << min;
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
using ll = long long;
mt19937 rng(1477);

const int MAXN = 3e3 + 10;

vector<int> g[MAXN];

#define int ll

signed main() {
#ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
//    freopen("output.txt", "w", stdout);
#endif
    ios_base::sync_with_stdio(0); cin.tie(0);

    int n;
    cin >> n;
    vector<int> a(n);
    for (auto &t : a) cin >> t;
    if (n > MAXN) {
        cout << 3;
        return 0;
    }
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < n; ++j) {
            if (i != j && (a[i] & a[j])) {
                g[i].push_back(j);
            }
        }
    }

    int res = 2 * n;
    for (int i = 0; i < n; ++i) {
        vector<int> dist(n, -1);
        dist[i] = 0;
        queue<int> que({i});
        while (!que.empty()) {
            int cur = que.front();
            que.pop();
            for (int to : g[cur]) {
                if (dist[to] == -1) {
                    que.push(to);
                    dist[to] = dist[cur] + 1;
                }
                else if (to != i) {
                    res = min(res, dist[to] + dist[cur] + 1);
                }
            }
        }
    }
    cout << (res == 2 * n ? -1 : res);
}


#include <bits/stdc++.h>
using namespace std;
using ll = long long;
mt19937 rng(1477);

#define int ll
const int MAXN = 40;
vector<int> g[MAXN];

signed main() {
#ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
//    freopen("output.txt", "w", stdout);
#endif
    ios_base::sync_with_stdio(0); cin.tie(0);

    int n;
    cin >> n;
    vector<int> b(n);
    for (auto &t : b) cin >> t;

    vector<int> a;
    for (auto &t : b) {
        if (t != 0) {
            a.push_back(t);
        }
    }

    n = a.size();
    if (n > MAXN) {
        cout << 3;
        return 0;
    }
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < n; ++j) {
            if (i != j && (a[i] & a[j])) {
                g[i].push_back(j);
            }
        }
    }

    int res = 2 * n;
    for (int i = 0; i < n; ++i) {
        vector<int> dist(n, -1);
        dist[i] = 0;
        queue<int> que({i});
        while (!que.empty()) {
            int cur = que.front();
            que.pop();
            for (int to : g[cur]) {
                if (dist[to] == -1) {
                    que.push(to);
                    dist[to] = dist[cur] + 1;
                }
                else if (dist[to] >= dist[cur]) {
                    res = min(res, dist[to] + dist[cur] + 1);
                }
            }
        }
    }
    cout << (res == 2 * n ? -1 : res);
}


#include <bits/stdc++.h>
using namespace std;
using ll = long long;
mt19937 rng(1477);

#define int ll
const int MAXN = 228;
vector<int> g[MAXN];

signed main() {
#ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
//    freopen("output.txt", "w", stdout);
#endif
    ios_base::sync_with_stdio(0); cin.tie(0);

    int n;
    cin >> n;
    vector<int> b(n);
    for (auto &t : b) cin >> t;

    vector<int> a;
    for (auto &t : b) {
        if (t != 0) {
            a.push_back(t);
        }
    }

    n = a.size();
    if (n > MAXN) {
        cout << 3;
        return 0;
    }
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < n; ++j) {
            if (i != j && (a[i] & a[j])) {
                g[i].push_back(j);
            }
        }
    }

    int res = 2 * n;
    for (int i = 0; i < n; ++i) {
        vector<int> dist(n, -1);
        dist[i] = 0;
        queue<int> que({i});
        while (!que.empty()) {
            int cur = que.front();
            que.pop();
            for (int to : g[cur]) {
                if (dist[to] == -1) {
                    que.push(to);
                    dist[to] = dist[cur] + 1;
                }
                else if (dist[to] >= dist[cur]) {
                    res = min(res, dist[to] + dist[cur] + 1);
                }
            }
        }
    }
    cout << (res == 2 * n ? -1 : res);
}


#include <bits/stdc++.h>
using namespace std;
using ll = long long;
mt19937 rng(1477);

#define int ll
const int MAXN = 40;
vector<int> g[MAXN];

signed main() {
#ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
//    freopen("output.txt", "w", stdout);
#endif
    ios_base::sync_with_stdio(0); cin.tie(0);

    int n;
    cin >> n;
    vector<int> b(n);
    for (auto &t : b) cin >> t;

    map<int, int> powtwo;
    for (int i = 0; i < 18; ++i) {
        powtwo[1LL << i] = 0;
    }
    vector<int> a;
    for (auto &t : b) {
        if (powtwo.count(t)) {
            powtwo[t]++;
        }
        else if (t != 0) {
            a.push_back(t);
        }
    }

    for (auto p : powtwo) {
        if (p.second >= 3) {
            cout << 3;
            return 0;
        }
    }

    n = a.size();
    if (n > MAXN) {
        cout << 3;
        return 0;
    }
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < n; ++j) {
            if (i != j && (a[i] & a[j])) {
                g[i].push_back(j);
            }
        }
    }

    int res = 2 * n;
    for (int i = 0; i < n; ++i) {
        vector<int> dist(n, -1);
        dist[i] = 0;
        queue<int> que({i});
        while (!que.empty()) {
            int cur = que.front();
            que.pop();
            for (int to : g[cur]) {
                if (dist[to] == -1) {
                    que.push(to);
                    dist[to] = dist[cur] + 1;
                }
                else if (to != i) {
                    res = min(res, dist[to] + dist[cur] + 1);
                }
            }
        }
    }
    cout << (res == 2 * n ? -1 : res);
}


#include <bits/stdc++.h>
using namespace std;
using ll = long long;
mt19937 rng(1477);

vector<int> g[100];

signed main() {
#ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
//    freopen("output.txt", "w", stdout);
#endif
    ios_base::sync_with_stdio(0); cin.tie(0);

    int n;
    cin >> n;
    vector<int> a(n);
    for (auto &t : a) cin >> t;
    if (n > 140) {
        cout << 3;
        return 0;
    }
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < n; ++j) {
            if (i != j && (a[i] & a[j])) {
                g[i].push_back(j);
            }
        }
    }

    int res = 2 * n;
    for (int i = 0; i < n; ++i) {
        vector<int> dist(n, -1);
        dist[i] = 0;
        queue<int> que({i});
        while (!que.empty()) {
            int cur = que.front();
            que.pop();
            for (int to : g[cur]) {
                if (dist[to] == -1) {
                    que.push(to);
                    dist[to] = dist[cur] + 1;
                }
                else if (to != i) {
                    res = min(res, dist[to] + dist[cur] + 1);
                }
            }
        }
    }
    cout << (res == 2 * n ? -1 : res);
}