import java.io.*;
import java.util.*;
import java.nio.charset.StandardCharsets;
// import java.math.BigInteger;

public class B {
    static Writer wr;

    static class State {
        public int u;
        public int v;
        public int d;
        public State(int a, int b, int dd) {
            u = a;
            v = b;
            d = dd;
        }

        public boolean equals(Object obj) {
            if (this == obj)
                return true;
            if (obj == null)
                return false;

            State other = (State)obj;
            if((other.u==u && other.v==v))
            {
                return true;
            }
            return false;
        }

        public int hashCode() {
            final int prime = 31;
            int result = 23;
            result = prime * result + u;
            result = prime * result + v;
            // result = prime * result + w;
            // System.out.print(result + " ");
            return result;
        }
    }

    public static void main(String[] args) throws Exception {
        // long startTime = System.nanoTime();

        // String testString = "";
        // InputStream stream = new ByteArrayInputStream(testString.getBytes(StandardCharsets.UTF_8));
        // Reader in = new Reader(stream);

        Reader in = new Reader();
        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));

        wr = new Writer();

        /* Precomputation */

        // long elapsedTime = System.nanoTime() - startTime;
        // double seconds = (double)elapsedTime / 1000000000.0;
        // wr.writeRedLn(seconds);

        /* Input */
        int r = in.nextInt();
        int x = in.nextInt();
        int y = in.nextInt();
        int x1 = in.nextInt();
        int y1 = in.nextInt();

        int dx[] = {1*r,-1*r,1*r,-1*r,2*r,-2*r,0,0};
        int dy[] = {1*r,-1*r,-1*r,1*r,0,0,2*r,-2*r};

        Queue<State> q = new LinkedList<>();
        State start = new State(x,y,0);
        q.add(start);

        HashSet<State> visited = new HashSet<>();
        visited.add(start);

        int ans = 0;
        outer:
        while(q.size()>0) {
            State curr = q.poll();
            // wr.writeRedLn(curr.u + ", " + curr.v + ", d: "  + curr.d);
            // if(curr.d==4) break;
            if((curr.u == x1) && (curr.v == y1)) {
                ans = curr.d;
                break outer;
            }
            for(int i=0;i<dx.length;i++) {

                State nx = new State(curr.u+dx[i],curr.v+dy[i], curr.d+1);
                // wr.writeBlueLn(nx.u + ", " + nx.v + ", d: "  + nx.d);

                if(!visited.contains(nx)) {
                    q.add(nx);
                    visited.add(nx);
                }
            }
        }

        out.write(ans + "\n");
        out.flush();
    }
}

class Writer {
    public void writeRedLn(Object x) { writeRedLn(x+""); }
    public void writeBlueLn(Object x) { writeBlueLn(x+""); }
    public void writeGreenLn(Object x) { writeGreenLn(x+""); }
    public void writePinkLn(Object x) { writePinkLn(x+""); }
    public void writeRedLn(String x) { System.out.println((char)27 + "[31m" + (char)27 + "[40m" + x + (char)27 + "[0m"); }
    public void writeBlueLn(String x) { System.out.println((char)27 + "[34m" + (char)27 + "[3m" + x + (char)27 + "[0m"); }
    public void writeGreenLn(String x) { System.out.println((char)27 + "[32m" + (char)27 + "[3m" + x + (char)27 + "[0m"); }
    public void writePinkLn(String x) { System.out.println((char)27 + "[30m" + (char)27 + "[45m" + x + (char)27 + "[0m"); }
    public void writeRed(String x) { System.out.print((char)27 + "[31m" + (char)27 + "[40m" + x + (char)27 + "[0m"); }
    public void writeBlue(String x) { System.out.print((char)27 + "[34m" + (char)27 + "[3m" + x + (char)27 + "[0m"); }
    public void writeGreen(String x) { System.out.print((char)27 + "[32m" + (char)27 + "[3m" + x + (char)27 + "[0m"); }
    public void writePink(String x) { System.out.print((char)27 + "[30m" + (char)27 + "[45m" + x + (char)27 + "[0m"); }
}

class Reader {
    public int LINE_LIMIT = -1;
    final private int BUFFER_SIZE = 1 << 16;private DataInputStream din;private byte[] buffer;private int bufferPointer, bytesRead;
    public Reader(){din=new DataInputStream(System.in);buffer=new byte[BUFFER_SIZE];bufferPointer=bytesRead=0;}
    public Reader(InputStream stream){din=new DataInputStream(stream);buffer=new byte[BUFFER_SIZE];bufferPointer=bytesRead=0;}
    public int[] ni_array(int N) throws IOException { int[] ans = new int[N]; for(int i=0;i<N;i++) { ans[i] = nextInt(); } return ans; }
    public String readLineUtil()throws IOException{byte[] buf=new byte[Math.max(400024,LINE_LIMIT)];int cnt=0,c;
        while((c=read())!=-1){if(c=='\n')break;buf[cnt++]=(byte)c;}return new String(buf,0,cnt);}
    public String readLine() throws IOException{ String line = readLineUtil().trim(); while(line.length()==0) line = readLineUtil().trim(); return line; }
    public char nextChar()throws IOException{byte c=read();while(c<=' ')c=read();return (char)c;}
    public int nextInt()throws IOException{int ret=0;byte c=read();while(c<=' ')c=read();boolean neg=(c=='-');
        if(neg)c=read();do{ret=ret*10+c-'0';}while((c=read())>='0'&&c<='9');if(neg)return -ret;return ret;}
    public long nextLong()throws IOException{long ret=0;byte c=read();while(c<=' ')c=read();boolean neg=(c=='-');
        if(neg)c=read();do{ret=ret*10+c-'0';}while((c=read())>='0'&&c<='9');if(neg)return -ret;return ret;}
    public double nextDouble()throws IOException{double ret=0,div=1;byte c=read();while(c<=' ')c=read();boolean neg=(c=='-');if(neg)c = read();do {ret=ret*10+c-'0';}while((c=read())>='0'&&c<='9');
        if(c=='.')while((c=read())>='0'&&c<='9')ret+=(c-'0')/(div*=10);if(neg)return -ret;return ret;}
    private void fillBuffer()throws IOException{bytesRead=din.read(buffer,bufferPointer=0,BUFFER_SIZE);if(bytesRead==-1)buffer[0]=-1;}
    private byte read()throws IOException{if(bufferPointer==bytesRead)fillBuffer();return buffer[bufferPointer++];}
    public void close()throws IOException{if(din==null) return;din.close();}
}


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
//package amrandpins;
import java.util.*;
/**
 *
 * @author Rawhi
 */
public class AmrAndPins {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int r = sc.nextInt(),x = sc.nextInt(),y = sc.nextInt(),xP = sc.nextInt(),yP = sc.nextInt();
        int totalSteps = 0, lastX = x, lastY = y;
        boolean flag = true;
        while (flag) {
            if(x < xP){
                x += r;
                if(lastY == yP){
                    x += r;
                }
                //System.out.println("X<");
            }else if( x > xP){
                //System.out.println("X>");
                x -= r;
                if(lastY == yP){
                    x -= r;
                }
            }else{
                //System.out.println("X=");
                if(y == yP){
                    break;
                }
            }
            if(y < yP){
                //System.out.println("Y<");
                y += r;
                if(lastX == xP){
                    y += r;
                }
            }else if( y > yP){
                //System.out.println("Y>");
                y -= r;
                if(lastX == xP){
                    y -= r;
                }
            }else{
                //System.out.println("Y=");
                if(x == xP && totalSteps != 0){
                    break;
                }
            }
            lastX = x;
            lastY = y;
            //System.out.println("Round");
            totalSteps++;
        }
        System.out.println(totalSteps);
    }

}


import java.util.Scanner;

public class Solution{

    Scanner sc = new Scanner(System.in);
    int x1 = sc.nextInt();
    int x2 = sc.nextInt();
    int x3 = sc.nextInt();

     int median = Math.max(Math.min(a,b), Math.min(Math.max(a,b),c));
     int total = 0;

    if(median != x1) total += Math.abs(median - x1);
    if(median != x2) total += Math.abs(median - x2);
    if(median != x3) total = Math.abs(median - x3);

    System.out.println(total);
}


import java.util.Scanner;
import java.util.*;

public class Main
{
    static Scanner in = new Scanner( System.in );

    public static void main( String[] args )
    {
        int a = in.nextInt();
        int b = in.nextInt();
        int c = in.nextInt();
        int sum = 0;
        while ( a != 1 || b != 1 || c != 1 )
        {
            sum += ( a + b + c ) * 2 - 6;
            a--; b--; c--;
        }
        sum += a * b * c;
        System.out.println( sum );
    }
}


 import java.util.Arrays;
import java.util.Scanner;

public class blah {

	public static void main(String[] args) {

		Scanner scan = new Scanner(System.in);
		int n = scan.nextInt();
		int k = scan.nextInt();	scan.nextLine();
		String s = scan.nextLine();
		int[] arr = new int[26];

		for (int i=0; i<n; i++) {
			arr[s.charAt(i) - 'a']++;
			System.out.println(s.charAt(i)-'a');
		}

		for (int i=0; i<26; i++) {
			if (arr[i] > k) {
				System.out.println("NO");
				return;
			}
		}
		System.out.println("YES");
	}

}


import java.io.*;
import java.util.*;
import java.math.BigInteger;
import java.util.Collections.*;
import static java.lang.Math.*;
import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.util.Arrays.*;
import static java.math.BigInteger.*;

public class Main{

    void run(){
        Locale.setDefault(Locale.US);
        boolean my;
        try {
            my = System.getProperty("MY_LOCAL") != null;
        } catch (Exception e) {
            my = false;

        }
        try{
            err = System.err;
            if( my ){
                sc  = new FastScanner(new BufferedReader(new FileReader("input.txt")));
//                sc  = new FastScanner(new BufferedReader(new FileReader("C:\\myTest.txt")));
                out = new PrintWriter   (new FileWriter("output.txt"));
            }
            else {
                sc = new FastScanner(new BufferedReader(new InputStreamReader(System.in)));
                out = new PrintWriter(new OutputStreamWriter(System.out));
            }
//            out = new PrintWriter(new OutputStreamWriter(System.out));
        }catch(Exception e){
            MLE();
        }
        if( my )
            tBeg = System.currentTimeMillis();
        solve();
        if( my )
            err.println( "TIME: " + (System.currentTimeMillis() - tBeg ) / 1e3 );
        exit(0);
    }

    void exit( int val ){
        err.flush();
        out.flush();
        System.exit(val);
    }

    double tBeg;
    FastScanner sc;
    PrintWriter out;
    PrintStream err;

    class FastScanner{

        StringTokenizer st;
        BufferedReader br;

        FastScanner( BufferedReader _br ){
            br = _br;
        }

        String readLine(){
            try {
                return br.readLine();
            } catch (IOException e) {
                return null;
            }
        }

        String next(){
            while( st==null || !st.hasMoreElements() )
                st = new StringTokenizer(readLine());
            return st.nextToken();
        }

        int nextInt(){ return Integer.parseInt(next()); }
        long nextLong(){ return Long.parseLong(next()); }
        double nextDouble(){ return Double.parseDouble(next()); }
    }

    void MLE(){
        int[][] arr = new int[1024*1024][]; for( int i = 0; i < 1024*1024; ++i ) arr[i] = new int[1024*1024];
    }

    void MLE( boolean doNotMLE ){ if( !doNotMLE ) MLE(); }

    void TLE(){
        for(;;);
    }

    public static void main(String[] args) {
        new Main().run();
//        new Thread( null, new Runnable() {
//            @Override
//            public void run() {
//                new Main().run();
//            }
//        }, "Lolka", 256_000_000L ).run();
    }

    ////////////////////////////////////////////////////////////////

    final int mod = (int)1e9 + 7;
    int n, k;
    Long[][] dp0, dp1;
    long[] pow2 = new long[1000];
    {
        pow2[0] = 1;
        for (int i = 1; i < pow2.length; i++) {
            pow2[i] = (pow2[i-1] * 2) % mod;
        }
    }

    void solve(){
        n = sc.nextInt();
        k = sc.nextInt();
        dp0 = new Long[k+1][n+1];
        for (Long[] val : dp0) fill(val, 0L);

        for (int sz = 1; sz <= n; sz++) {
            dp1  = new Long[k+1][n+1];

            for (int cnt  = 0; cnt <= k; cnt++) {
            for (int last = 0; last <= sz; last++) {
                if( cnt == 0 ){
                    if( last == 0 ) dp1[cnt][last] = 1L;
                    else dp1[cnt][last] = 0L;
                }
                else if( sz == last ){
                    if( cnt == 1 ){
                        dp1[cnt][last] = (pow2[last]-1);
                    }
                    else{
                        dp1[cnt][last] = 0L;
                        for (int l = 1; l <= sz - 1; l++) {
                            dp1[cnt][last] += dp1[cnt-1][l] * (pow2[sz-l]-1);
                        }
                    }
                }
                else{
                    dp1[cnt][last] = dp0[cnt][last] * pow2[last];
                }
                dp1[cnt][last] = ( dp1[cnt][last]%mod + mod ) % mod;
            }
            }
            //
            dp0 = dp1;
        }
        long ans = 0;
        for (int last = 0; last <= n; last++) {
            ans += dp0[k][last];
        }
        ans %= mod;
        out.println( ans );
    }

}


import java.io.*;
import java.util.*;
import java.math.BigInteger;
import java.util.Collections.*;
import static java.lang.Math.*;
import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.util.Arrays.*;
import static java.math.BigInteger.*;

public class Main{

    void run(){
        Locale.setDefault(Locale.US);
        boolean my;
        try {
            my = System.getProperty("MY_LOCAL") != null;
        } catch (Exception e) {
            my = false;

        }
        try{
            err = System.err;
            if( my ){
                sc  = new FastScanner(new BufferedReader(new FileReader("input.txt")));
//                sc  = new FastScanner(new BufferedReader(new FileReader("C:\\myTest.txt")));
                out = new PrintWriter   (new FileWriter("output.txt"));
            }
            else {
                sc = new FastScanner(new BufferedReader(new InputStreamReader(System.in)));
                out = new PrintWriter(new OutputStreamWriter(System.out));
            }
//            out = new PrintWriter(new OutputStreamWriter(System.out));
        }catch(Exception e){
            MLE();
        }
        if( my )
            tBeg = System.currentTimeMillis();
        solve();
        if( my )
            err.println( "TIME: " + (System.currentTimeMillis() - tBeg ) / 1e3 );
        exit(0);
    }

    void exit( int val ){
        err.flush();
        out.flush();
        System.exit(val);
    }

    double tBeg;
    FastScanner sc;
    PrintWriter out;
    PrintStream err;

    class FastScanner{

        StringTokenizer st;
        BufferedReader br;

        FastScanner( BufferedReader _br ){
            br = _br;
        }

        String readLine(){
            try {
                return br.readLine();
            } catch (IOException e) {
                return null;
            }
        }

        String next(){
            while( st==null || !st.hasMoreElements() )
                st = new StringTokenizer(readLine());
            return st.nextToken();
        }

        int nextInt(){ return Integer.parseInt(next()); }
        long nextLong(){ return Long.parseLong(next()); }
        double nextDouble(){ return Double.parseDouble(next()); }
    }

    void MLE(){
        int[][] arr = new int[1024*1024][]; for( int i = 0; i < 1024*1024; ++i ) arr[i] = new int[1024*1024];
    }

    void MLE( boolean doNotMLE ){ if( !doNotMLE ) MLE(); }

    void TLE(){
        for(;;);
    }

    public static void main(String[] args) {
        new Main().run();
//        new Thread( null, new Runnable() {
//            @Override
//            public void run() {
//                new Main().run();
//            }
//        }, "Lolka", 256_000_000L ).run();
    }

    ////////////////////////////////////////////////////////////////

    final long mod = (int)1e9 + 7;
    int n, k;
    Long[][] dp0, dp1;
    long[] pow2 = new long[1000];
    {
        pow2[0] = 1;
        for (int i = 1; i < pow2.length; i++) {
            pow2[i] = (pow2[i-1] * 2) % mod;
        }
    }

    void solve(){
        n = sc.nextInt();
        k = sc.nextInt();
        dp0 = new Long[k+1][n+1];
        for (Long[] val : dp0) fill(val, 0L);

        for (int sz = 1; sz <= n; sz++) {
            dp1  = new Long[k+1][n+1];

            for (int cnt  = 0; cnt <= k; cnt++) {
            for (int last = 0; last <= sz; last++) {
                if( cnt == 0 ){
                    if( last == 0 ) dp1[cnt][last] = 1L;
                    else dp1[cnt][last] = 0L;
                }
                else if( sz == last ){
                    if( cnt == 1 ){
                        dp1[cnt][last] = (pow2[last]-1);
                    }
                    else{
                        dp1[cnt][last] = 0L;
                        for (int l = 1; l <= sz - 1; l++) {
                            dp1[cnt][last] += (dp1[cnt-1][l] * (pow2[sz-l]-1)) % mod;
                        }
                    }
                }
                else{
                    dp1[cnt][last] = dp0[cnt][last] * pow2[last];
                }
                dp1[cnt][last] = ( dp1[cnt][last]%mod + mod ) % mod;
            }
            }
            //
            dp0 = dp1;
        }
        long ans = 0;
        for (int last = 0; last <= n; last++) {
            ans += dp0[k][last];
        }
        ans %= mod;
        out.println( ans );
    }

}


import java.io.*;
import java.util.*;
import java.math.BigInteger;
import java.util.Collections.*;
import static java.lang.Math.*;
import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.util.Arrays.*;
import static java.math.BigInteger.*;

public class Main{

    void run(){
        Locale.setDefault(Locale.US);
        boolean my;
        try {
            my = System.getProperty("MY_LOCAL") != null;
        } catch (Exception e) {
            my = false;

        }
        try{
            err = System.err;
            if( my ){
                sc  = new FastScanner(new BufferedReader(new FileReader("input.txt")));
//                sc  = new FastScanner(new BufferedReader(new FileReader("C:\\myTest.txt")));
                out = new PrintWriter   (new FileWriter("output.txt"));
            }
            else {
                sc = new FastScanner(new BufferedReader(new InputStreamReader(System.in)));
                out = new PrintWriter(new OutputStreamWriter(System.out));
            }
//            out = new PrintWriter(new OutputStreamWriter(System.out));
        }catch(Exception e){
            MLE();
        }
        if( my )
            tBeg = System.currentTimeMillis();
        solve();
        if( my )
            err.println( "TIME: " + (System.currentTimeMillis() - tBeg ) / 1e3 );
        exit(0);
    }

    void exit( int val ){
        err.flush();
        out.flush();
        System.exit(val);
    }

    double tBeg;
    FastScanner sc;
    PrintWriter out;
    PrintStream err;

    class FastScanner{

        StringTokenizer st;
        BufferedReader br;

        FastScanner( BufferedReader _br ){
            br = _br;
        }

        String readLine(){
            try {
                return br.readLine();
            } catch (IOException e) {
                return null;
            }
        }

        String next(){
            while( st==null || !st.hasMoreElements() )
                st = new StringTokenizer(readLine());
            return st.nextToken();
        }

        int nextInt(){ return Integer.parseInt(next()); }
        long nextLong(){ return Long.parseLong(next()); }
        double nextDouble(){ return Double.parseDouble(next()); }
    }

    void MLE(){
        int[][] arr = new int[1024*1024][]; for( int i = 0; i < 1024*1024; ++i ) arr[i] = new int[1024*1024];
    }

    void MLE( boolean doNotMLE ){ if( !doNotMLE ) MLE(); }

    void TLE(){
        for(;;);
    }

    public static void main(String[] args) {
        new Main().run();
//        new Thread( null, new Runnable() {
//            @Override
//            public void run() {
//                new Main().run();
//            }
//        }, "Lolka", 256_000_000L ).run();
    }

    ////////////////////////////////////////////////////////////////

    final int mod = (int)1e9 + 7;
    int n, k;
    long[][] dp0, dp1;
    long[] pow2 = new long[600];
    {
        pow2[0] = 1;
        for (int i = 1; i < pow2.length; i++) {
            pow2[i] = (pow2[i-1] * 2) % mod;
        }
    }

    void solve(){
        n = sc.nextInt();
        k = sc.nextInt();
        dp0 = new long[k+1][n+1];
        for (long[] val : dp0) fill(val, 0L);

        for (int sz = 1; sz <= n; sz++) {
            dp1  = new long[k+1][n+1];

            for (int cnt  = 0; cnt <= k; cnt++) {
                for (int last = 0; last <= sz; last++) {
                    if( cnt == 0 ){
                        if( last == 0 ) dp1[cnt][last] = 1L;
                        else dp1[cnt][last] = 0L;
                    }
                    else if( sz == last ){
                        if( cnt == 1 ){
                            dp1[cnt][last] = pow2[last] - 1;
                        }
                    }
                    else{
                        dp1[cnt][last] = (dp0[cnt][last] * pow2[last]) % mod;
                    }
                    dp1[cnt][last] = dp1[cnt][last];

                    if( 1<=last && last <= sz-1   &&   1 <= cnt && cnt+1 <= k ){
                        dp1[cnt+1][sz] += (dp1[cnt][last] * (pow2[sz-last]-1)) % mod;
                    }
                }
            }
           //
            dp0 = dp1;
        }
        long ans = 0;
        for (int last = 0; last <= n; last++) {
            ans += dp0[k][last];
        }
        ans %= mod;
        out.println( ans );
    }

}


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package robot;

import java.util.Scanner;

/**
 *
 * @author KaYdaz
 */
public class Robot {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        Scanner scan = new Scanner(System.in);
        int n = Integer.parseInt(scan.nextLine());
        String ch = scan.nextLine();
        int nbr_move=0;
        boolean b = true;
        while (b)
        {
            if ((ch.contains("U")&&ch.contains("D")))
            {
                ch = ch.replaceFirst("U", "");
                ch = ch.replaceFirst("D", "");
                nbr_move+=2;
            }
            else if (ch.contains("L")&&ch.contains("R"))
            {
                ch = ch.replaceFirst("L", "");
                ch = ch.replaceFirst("R", "");
                nbr_move+=2;
            }
            else b = false;
        }
        System.out.println(nbr_move);
    }

}


package main;

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

public class main {

	public static void main(String[] args) {
		Scanner input =new Scanner(System.in);
		int quan= input.nextInt();
		Scanner input2 =new Scanner(System.in);
		String command= input2.next();
		int upA=0,downA=0,leftA=0,rightA=0;
		for (int i=0;i<quan;i++){
			switch (command.charAt(i)){
			case 'U':upA++;
				break;
			case 'D':downA++;
				break;
			case 'L':leftA++;
				break;
			case 'R':rightA++;
				break;
			}
		}
		quan=(Math.abs(upA-downA)+Math.abs(rightA-leftA));
		System.out.println(quan);

}
}


import java.io.IOException;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) throws IOException {
        Scanner sc = new Scanner(System.in);

        int n=sc.nextInt(), i, j=0, im=0, zero=0, one=0, km=0, result=0;
        int[] arr = new int[n];
        int[] zeros = new int[n/2];
        boolean onlyOne=true;
        arr[0]=sc.nextInt();
        for(i=1; i<n; i++)
        {
            arr[i]=sc.nextInt();

        }
        i=1;
        while (km+im<arr.length &&( i< arr.length || j<arr.length))
        {
            if (j<arr.length && arr[j]==1)
            {
                j++;
                im++;
            }
            else
                j=arr.length;

            if ( i<arr.length && arr[arr.length-i]==1 && km<im)
            {
                i++;
                km++;
            }
            else
                i=arr.length;
        }

        for(i=im; i<n; i++)
        {

            if (arr[i]==0)
                zero++;
            else
                one++;
        }
        result=im+Math.max(zero, one)+km;
        j=0;
        while (onlyOne && j<arr.length)
        {

        }
        System.out.println(result);
    }
}


import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.SortedSet;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;

/**
 * #
 *
 * @author pttrung
 */
public class B_8VC_2016_Final_Div1 {

	public static long MOD = 1000000007;

	public static void main(String[] args) throws FileNotFoundException {
		// PrintWriter out = new PrintWriter(new FileOutputStream(new File(
		// "output.txt")));
		PrintWriter out = new PrintWriter(System.out);
		Scanner in = new Scanner();
		long sum = in.nextLong();
		long x = in.nextLong();
		long result = cal(0, 0, 0, 0, x, sum);
		out.println(result);
		out.close();
	}

	public static long cal(int index, int add, int posA, int posB, long x,
			long sum) {
		if (index == 63) {
			if (posA == 1 && posB == 1 && add == 0)
				return 1;
			return 0;
		}
		int one = (((1L << index) & x) != 0) ? 1 : 0;
		int s = (((1L << index) & sum) != 0) ? 1 : 0;
		long result = 0;
		for (int i = 0; i < 2; i++) {
			int other = one ^ i;
			int v = other + i + add;
			if ((v & 1) == s) {
				result += cal(index + 1, v >> 1, i == 1 ? 1 : posA,
						other == 1 ? 1 : posB, x, sum);
			}
		}
		return result;
	}

	public static int[] KMP(String val) {
		int i = 0;
		int j = -1;
		int[] result = new int[val.length() + 1];
		result[0] = -1;
		while (i < val.length()) {
			while (j >= 0 && val.charAt(j) != val.charAt(i)) {
				j = result[j];
			}
			j++;
			i++;
			result[i] = j;
		}
		return result;

	}

	public static boolean nextPer(int[] data) {
		int i = data.length - 1;
		while (i > 0 && data[i] < data[i - 1]) {
			i--;
		}
		if (i == 0) {
			return false;
		}
		int j = data.length - 1;
		while (data[j] < data[i - 1]) {
			j--;
		}
		int temp = data[i - 1];
		data[i - 1] = data[j];
		data[j] = temp;
		Arrays.sort(data, i, data.length);
		return true;
	}

	public static int digit(long n) {
		int result = 0;
		while (n > 0) {
			n /= 10;
			result++;
		}
		return result;
	}

	public static double dist(long a, long b, long x, long y) {
		double val = (b - a) * (b - a) + (x - y) * (x - y);
		val = Math.sqrt(val);
		double other = x * x + a * a;
		other = Math.sqrt(other);
		return val + other;

	}

	public static class Point implements Comparable<Point> {

		int x, y;

		public Point(int start, int end) {
			this.x = start;
			this.y = end;
		}

		@Override
		public int hashCode() {
			int hash = 5;
			hash = 47 * hash + this.x;
			hash = 47 * hash + this.y;
			return hash;
		}

		@Override
		public boolean equals(Object obj) {
			if (obj == null) {
				return false;
			}
			if (getClass() != obj.getClass()) {
				return false;
			}
			final Point other = (Point) obj;
			if (this.x != other.x) {
				return false;
			}
			if (this.y != other.y) {
				return false;
			}
			return true;
		}

		@Override
		public int compareTo(Point o) {
			return x - o.x;
		}
	}

	public static class FT {

		long[] data;

		FT(int n) {
			data = new long[n];
		}

		public void update(int index, long value) {
			while (index < data.length) {
				data[index] += value;
				index += (index & (-index));
			}
		}

		public long get(int index) {
			long result = 0;
			while (index > 0) {
				result += data[index];
				index -= (index & (-index));
			}
			return result;

		}
	}

	public static long gcd(long a, long b) {
		if (b == 0) {
			return a;
		}
		return gcd(b, a % b);
	}

	public static long pow(long a, long b) {
		if (b == 0) {
			return 1;
		}
		if (b == 1) {
			return a;
		}
		long val = pow(a, b / 2);
		if (b % 2 == 0) {
			return val * val % MOD;
		} else {
			return val * (val * a % MOD) % MOD;

		}
	}

	static class Scanner {

		BufferedReader br;
		StringTokenizer st;

		public Scanner() throws FileNotFoundException {
			// System.setOut(new PrintStream(new
			// BufferedOutputStream(System.out), true));
			br = new BufferedReader(new InputStreamReader(System.in));
			// br = new BufferedReader(new InputStreamReader(new
			// FileInputStream(new File("input.txt"))));
		}

		public String next() {

			while (st == null || !st.hasMoreTokens()) {
				try {
					st = new StringTokenizer(br.readLine());
				} catch (Exception e) {
					throw new RuntimeException();
				}
			}
			return st.nextToken();
		}

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

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

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

		public String nextLine() {
			st = null;
			try {
				return br.readLine();
			} catch (Exception e) {
				throw new RuntimeException();
			}
		}

		public boolean endLine() {
			try {
				String next = br.readLine();
				while (next != null && next.trim().isEmpty()) {
					next = br.readLine();
				}
				if (next == null) {
					return true;
				}
				st = new StringTokenizer(next);
				return st.hasMoreTokens();
			} catch (Exception e) {
				throw new RuntimeException();
			}
		}
	}
}


import java.util.*;
import java.io.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.MathContext;

public class Es
{
	static class P implements Comparable
	{
		int first;
		int second;

		public P(int f, int s)
		{
			first = f;
			second = s;
		}

		public String toString()
		{
			return first + " " + second;
		}

		public int compareTo(Object o)
		{
			P p2 = (P)o;
			if(this.first - this.second > p2.first - p2.second)
				return -1;
			if(this.first - this.second < p2.first - p2.second)
				return 1;
			return 0;
		}
	}

	static int log2(double a)
	{
		return (int)(Math.log(a) / Math.log(2));
	}

	static long gcd(long a, long b)
	{
		long r;
		while((r = a % b) > 0)
		{
			a = b;
			b = r;
		}
		return b;
	}

	static long ans = 0;
	static int n, m;

	static void fun(long[] v, int i, long curr)
	{
		for(int j = i; j < n; j ++)
		{
			long possibleAns = (curr + v[j]) % m;
			if(m - ans > m - possibleAns)
				ans = possibleAns;
			fun(v, j + 1, possibleAns);
		}
	}

	public static void main(String[] args) throws IOException
	{
		n = in.nextInt();
		m = in.nextInt();
		long[] v = new long[n];
		for(int i = 0; i < n; i ++)
			v[i] = in.nextLong() % m;
		fun(v, 0, 0);
		sop(ans);
	}

	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;
        }
    }

    static FastReader in = new FastReader();

    public static void sop(Object o)
    {
    	System.out.print(o);
    }
}


import java.util.*;
import java.io.*;
public class A
{
      public static void main(String ar[]) throws Exception
      {
            BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
            String s1[]=br.readLine().split(" ");
            String s2[]=br.readLine().split(" ");

            int n=Integer.parseInt(s1[0]);
            long m=Long.parseLong(s1[1]);

            int l1=n/2;
            int l2=n-n/2;
            long a[]=new long[l1];
            long b[]=new long[l2];
            for(int i=0;i<l1;i++)
             a[i]=Long.parseLong(s2[i]);
            for(int i=l1;i<n;i++)
             b[i-l1]=Long.parseLong(s2[i]);

            ArrayList<Long> al1=new ArrayList<Long>();
            ArrayList<Long> al2=new ArrayList<Long>();
            long ll1=(long)Math.pow(2,l1)-1;
            long ll2=(long)Math.pow(2,l2)-1;
            for(int i=0;i<=ll1;i++)
            {
                  int u=i;
                  int j=0;
                  long S=0;
                  while(u>0)
                  {
                        if(u%2==1)
                         S+=a[j];
                        u=u/2; j++;
                  }
                  al1.add(S%m);
            }

            for(int i=0;i<=ll2;i++)
            {
                  int u=i;
                  int j=0;
                  long S=0;
                  while(u>0)
                  {
                        if(u%2==1)
                         S+=b[j];
                        u=u/2; j++;
                  }
                  al2.add(S%m);
            }

            Collections.sort(al1);
            Collections.sort(al2);
            long t=0;
            for(int i=0;i<al1.size();i++)
            {
                  long x=m-al1.get(i);
                  int u=Collections.binarySearch(al2,x);

                  u=Math.abs(u+2);
                  t=Math.max(t,(al1.get(i)+al2.get(u))%m);
            }

            //System.out.println(al1);
            //System.out.println(al2);

            System.out.println(t);
      }
}


import javax.xml.crypto.dsig.keyinfo.KeyValue;
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;

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);
        TaskC solver = new TaskC();
        solver.Solve(in, out);
        out.close();
    }

    static class TaskC {

        public void Solve(InputReader in, PrintWriter out) {
            int n = in.NextInt();
            int m = in.NextInt();
            int[] a = in.NextIntArray(n);
            HashSet<Integer> hs = new HashSet<>();
            hs.add(0);
            for (int i = 0; i < n; i++) {
                ArrayList<Integer> aa = new ArrayList<>();
                for (int j : hs) {
                    aa.add((j + a[i]) % m);
                }
                hs.addAll(aa);
            }
            int res = 0;
            for (int j : hs) {
                res = Math.max(res, j);
            }
            out.println(res);

        }

    }

    public static int GetMax(int[] ar) {
        int max = Integer.MIN_VALUE;
        for (int a : ar) {
            max = Math.max(max, a);
        }
        return max;
    }

    public static int GetMin(int[] ar) {
        int min = Integer.MAX_VALUE;
        for (int a : ar) {
            min = Math.min(min, a);
        }
        return min;
    }

    public static long GetSum(int[] ar) {
        long s = 0;
        for (int a : ar) s += a;
        return s;
    }

    public static int[] GetCount(int[] ar) {
        return GetCount(ar, GetMax(ar));
    }

    public static int[] GetCount(int[] ar, int maxValue) {
        int[] dp = new int[maxValue + 1];
        for (int a : ar) {
            dp[a]++;
        }
        return dp;
    }

    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(), " \t\n\r\f,");
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken();
        }

        public int NextInt() {
            return Integer.parseInt(Next());
        }

        public long NextLong() {
            return Long.parseLong(Next());
        }

        public double NextDouble() {
            return Double.parseDouble(Next());
        }

        public int[] NextIntArray(int n) {
            return NextIntArray(n, 0);
        }

        public int[] NextIntArray(int n, int offset) {
            int[] a = new int[n];
            for (int i = 0; i < n; i++) {
                a[i] = NextInt() - offset;
            }
            return a;
        }

        public int[][] NextIntMatrix(int n, int m) {
            return NextIntMatrix(n, m, 0);
        }

        public int[][] NextIntMatrix(int n, int m, int offset) {
            int[][] a = new int[n][m];
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++) {
                    a[i][j] = NextInt() - offset;
                }
            }
            return a;
        }
    }
}


import java.util.*;
import java.io.*;
import java.io.FileWriter;
import java.math.BigInteger;
import java.math.BigDecimal;
// Solution

public class Main
{
  public static void main (String[] argv)
  {
	  new Main();
  }

  boolean test = false;
  final int[][] dirs8 = {{0,1}, {0,-1}, {-1,0}, {1,0}, {1,1},{1,-1},{-1,1},{-1,-1}};
  final int[][] dirs4 = {{0,1}, {0,-1}, {-1,0}, {1,0}};
  final int MOD = 1000000007;  //998244353;

  final int WALL = -1;
  final int EMPTY = -2;
  final int VISITED = 1;
  final int FULL = 2;

  final int START = 1;
  final int END = 0;

  int[] fac;
  int[] ifac;
  int[] rfac;

  int[] pow2;

  int[] mobius;
  int[] sieve;
  int[][] factors;

  int[][] dp;
         final int OK = Integer.MAX_VALUE;

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

    //FastReader in = new FastReader(new BufferedReader(new FileReader("Main.in")));

    //int nt = in.nextInt();
    int nt = 1;
    StringBuilder sb = new StringBuilder();

    for (int it = 0; it < nt; it++)
    {
       //long k = in.nextLong();

       int n = in.nextInt();
       int m = in.nextInt();
       int[] a = new int[n];

       for (int i = 0; i < n; i++) {
           a[i] = in.nextInt() % m;
       }
       int mid = (n-1)/2;
       Integer[] lvals = build(a, 0, mid, m);
       Integer[] rvals = build(a, mid+1, n - 1, m);
       int llen = lvals.length;
       int rlen = rvals.length;
       int lmax = lvals[llen - 1];
       int rmax = rvals[rlen - 1];
       if (lmax == m - 1 || rmax == m - 1) {
           System.out.println(m-1);
           return;
       }

       int max = Math.max(lmax, rmax);
       for (int i = 0, j = rlen - 1; i < llen; i++) {
           int tgt = m - 1 - lvals[i];
           while (j >= 0 && rvals[j] > tgt) j--;
           if (j < 0) break;
           max = Math.max(max, rvals[j] + lvals[i]);
       }
       System.out.println(max);
    }

    System.out.print(sb);
  }

  private Integer[] build(int[] a, int lo, int hi, int m)
  {
      int n = hi - lo + 1;
      int S = (1 << n);
      Integer[] ans = new Integer[S-1];
      int k = 0;
      for (int i = 1; i < S; i++)
      {
          int sum = 0;
          for (int j = 0; j < n; j++)
          {
              if (((i >>> j) & 1) != 0){
                  //pick current location
                  sum += a[j+lo];
                  if (sum >= m) sum -= m;
              }
          }
          ans[k++] = sum;
      }
      Arrays.sort(ans);
      return ans;
  }

  class Node implements Comparable<Node>{
      int lo, hi;
      public Node(int lo, int hi)
      {
          this.lo = lo;
          this.hi = hi;
      }

      @Override
      public int compareTo(Node o){
          if (lo != o.lo) return lo - o.lo;
          return hi - o.hi;
      }
  }

  private long[][] matIdentity(int n)
  {
      long[][] a = new long[n][n];
      for (int i = 0; i < n; i++)
          a[i][i] = 1;
      return a;
  }
  private long[][] matPow(long[][] mat0, long p)
  {
      int n = mat0.length;
      long[][] ans = matIdentity(n);
      long[][] mat = matCopy(mat0);
      while (p > 0)
      {
          if (p % 2 == 1){
              ans = matMul(ans, mat);
          }

          p /= 2;
          mat = matMul(mat, mat);
      }
      return ans;
  }

  private long[][] matCopy(long[][] a)
  {
      int n = a.length;
      long[][] b = new long[n][n];
      for (int i = 0; i < n; i++)
          for (int j = 0; j < n; j++)
              b[i][j] = a[i][j];
      return b;
  }
  private long[][] matMul(long[][] a, long[][] b)
  {
      int n = a.length;

      long[][] c = new long[n][n];
      for (int i = 0; i < n; i++)
      {
          for (int j = 0; j < n; j++)
          {
              for (int k = 0; k < n; k++)
                  c[i][j] = (c[i][j] + a[i][k] * b[k][j]) % MOD;
          }
      }

      return c;
  }

  private long[] matMul(long[][] a, long[] b)
  {
      int n = a.length;

      long[] c = new long[n];
      for (int i = 0; i < n; i++)
      {
          for (int j = 0; j < n; j++)
              c[i] = (c[i] + a[i][j] * b[j]) % MOD;
      }

      return c;
  }

  class Mark implements Comparable<Mark> {
      int type, h;
      long x;
      public Mark(int h, long x, int type)
      {
         this.h = h;
         this.x = x;
         this.type = type;
      }

      @Override
      public int compareTo(Mark o)
      {
          if (this.x == o.x) return type - o.type; // let end comes before start
          return Long.compare(x, o.x);
      }
  }

  private boolean coLinear(int[] p, int[] q, int[] r)
  {
      return 1L * (p[1] - r[1]) * (q[0] - r[0]) == 1L * (q[1] - r[1]) * (p[0] - r[0]);
  }

  private void fill(char[] a, int lo, int c, char letter)
  {
      //System.out.println("fill " + lo + " " + c + " " + letter);
      for (int i = lo; i < lo + c; i++) a[i] = letter;
  }

  private int cntBitOne(String s){
      int c = 0, n = s.length();
      for (int i = 0; i < n; i++)
          if (s.charAt(i) == '1') c++;
      return c;
  }

  class DSU {
      int n;
      int[] par;
      int[] sz;
      int nGroup;

      public DSU(int n)
      {
          this.n = n;
          par = new int[n];
          sz = new int[n];
          for (int i = 0;  i < n; i++){
              par[i] = i;
              sz[i] = 1;
          }
          nGroup = n;
      }

      private boolean add(int p, int q) {
          int rp = find(p);
          int rq = find(q);
          if (rq == rp) return false;

          if (sz[rp] <= sz[rq]) {
              sz[rq] += sz[rp];
              par[rp] = rq;
          }else {
              sz[rp] += sz[rq];
              par[rq] = rp;
          }
          nGroup--;
          return true;
      }

      private int find(int p)
      {
          int r = p;
          while (par[r] != r) r = par[r];

          while (r != p) {
              int t = par[p];
              par[p] = r;
              p = t;
          }
          return r;
      }

  }

  // μ(n) = 1 if n is a square-free positive integer with an even number of prime factors. e.g.  6, 15
  // μ(n) = −1 if n is a square-free positive integer with an odd number of prime factors. e.g.  2, 3, 5, 2*3*5
  // μ(n) = 0 if n has a squared prime factor. e.g : 2*2,  3*3*5
  private void build_pow2_function(int n)
  {
      pow2 = new int[n+1];
       pow2[0] = 1;
       for (int i = 1; i <= n; i++) pow2[i] = (int)(1L * pow2[i-1] * 2 % MOD);
  }

  private void build_fac_function(int n)
  {
      fac = new int[n+1];
      fac[0] = 1;
      for (int i = 1; i <= n; i++)
          fac[i] = (int)(1L * fac[i-1] * i % MOD);
  }

  private void build_ifac_function(int n)
  {
      ifac = new int[n+1];
      ifac[0] = 1;
      for (int i = 1; i <= n; i++)
          ifac[i] = (int)(1L * ifac[i-1] * inv(i) % MOD);
  }

  private void build_sieve_function(int n)
  {
      sieve = new int[n+1];
      for (int i = 2; i <= n; i++)
        sieve[i] = i;
      for (int i = 2; i <= n; i++)
      {
        if (sieve[i] == i){
            for (long j = 1L * i * i; j <= n; j += i)
                sieve[(int)j] = i;
        }
      }
  }

  private void build_mobius_function(int n)
  {
      mobius = new int[n+1];
      sieve = new int[n+1];
      factors = new int[n+1][];
      //for (int i = 1; i <= n; i++)factors[i] = new ArrayList<>();
      for (int i = 2; i <= n; i++)
        sieve[i] = i;
      for (int i = 2; i <= n; i++)
      {
        if (sieve[i] == i){
            mobius[i] = -1;
            for (long j = 1L * i * i; j <= n; j += i)
                sieve[(int)j] = i;
        }
      }

      for (int i = 6; i <= n; i++)
      {
          if (sieve[i] != i) {
              int pre = i / sieve[i];
              if (pre % sieve[i] != 0)
                  mobius[i] = -mobius[pre];
          }
      }
      int[] sz = new int[n+1];
      long tot = 0;
      for (int i = 2; i <= n; i++)
      {
          if (mobius[i] != 0)
          {
              for (int j = i * 2; j <= n; j += i) {
                  sz[j]++;
                  tot++;
              }
          }
      }
      for (int i = 2; i <= n; i++) {
          factors[i] = new int[sz[i]];
          sz[i] = 0;
      }

      for (int i = 2; i <= n; i++)
      {
          if (mobius[i] != 0)
          {
              for (int j = i * 2; j <= n; j += i) {
                  factors[j][sz[j]++] = i;
                  //factors[j].add(i);
              }
          }
      }
      //System.out.println("tot  =  "  + tot);
  }

  private int[] build_z_function(String s)
  {
      int n = s.length();
      int[] zfun = new int[n];

      int l = -1, r = -1;
      for (int i = 1; i < n; i++)
      {
         // Set the start value
         if (i <= r)
            zfun[i] = Math.min(zfun[i-l], r - i + 1);

         while (i + zfun[i] < n && s.charAt(i + zfun[i]) == s.charAt(zfun[i]))
             zfun[i]++;

         if (i + zfun[i] - 1> r){
             l = i;
             r = i + zfun[i] - 1;
         }
      }

      if (test)
      {
          System.out.println("Z-function of " + s);
          for (int i = 0; i < n; i++) System.out.print(zfun[i] + " ");
          System.out.println();
      }
      return zfun;
  }

  class BIT {
      int[] bit;
      int n;

      public BIT(int n){
          this.n = n;
          bit = new int[n+1];
      }

      private int query(int p)
      {
          int sum = 0;
          for (; p > 0; p -= (p & (-p)))
             sum += bit[p];

          return sum;
      }

      private void add(int p, int val)
      {
         //System.out.println("add to BIT " + p);
         for (; p <= n; p += (p & (-p)))
            bit[p] += val;
      }

  }

  private List<Integer> getMinFactor(int sum)
  {
      List<Integer>  factors = new ArrayList<>();

               for (int sz = 2; sz <= sum / sz; sz++){
                   if (sum % sz == 0) {
                       factors.add(sz);
                       factors.add(sum / sz);
                   }
               }
               if (factors.size() == 0)
                   factors.add(sum);

      return factors;
  }

  /* Tree class */
  class Tree {
      int V = 0;
      int root = 0;
      List<Integer>[] nbs;
      int[][] timeRange;
      int[] subTreeSize;
      int t;
      boolean dump = false;

      public Tree(int V, int root)
      {
          if (dump)
              System.out.println("build tree with size = " + V + ", root = " + root);

          this.V = V;
          this.root = root;
          nbs = new List[V];
          subTreeSize = new int[V];
          for (int i = 0; i < V; i++)
              nbs[i] = new ArrayList<>();

      }

      public void doneInput()
      {
          dfsEuler();
      }

      public void addEdge(int p, int q)
      {
          nbs[p].add(q);
          nbs[q].add(p);
      }

      private void dfsEuler()
      {
          timeRange = new int[V][2];
          t = 1;
          dfs(root);
      }

      private void dfs(int node)
      {
          if (dump)
              System.out.println("dfs on node " + node + ", at time " + t);
          timeRange[node][0] = t;

          for (int next : nbs[node]) {
              if (timeRange[next][0] == 0)
              {
                  ++t;
                  dfs(next);
              }
          }
          timeRange[node][1] = t;
          subTreeSize[node] = t - timeRange[node][0] + 1;
      }

      public List<Integer> getNeighbors(int p) {
          return nbs[p];
      }

      public int[] getSubTreeSize(){
          return subTreeSize;
      }

      public int[][] getTimeRange()
      {
          if (dump){
              for (int i = 0; i < V; i++){
                  System.out.println(i + ": " + timeRange[i][0] + " - " + timeRange[i][1]);
              }
          }
          return timeRange;
      }

  }

  /* segment tree */
  class SegTree {
      int[] a;
      int[] tree;
      int[] treeMin;
      int[] treeMax;
      int[] lazy;
      int n;
      boolean dump = false;

      public SegTree(int n)
      {
          if (dump)
              System.out.println("create segTree with size " + n);
          this.n = n;
          treeMin = new int[n*4];
          treeMax = new int[n*4];
          lazy = new int[n*4];
      }

      public SegTree(int n, int[] a) {
          this(n);
          this.a = a;
          buildTree(1, 0, n-1);
      }

      private void buildTree(int node, int lo, int hi)
      {
          if (lo == hi) {
              tree[node] = lo;
              return;
          }

          int m = (lo + hi) / 2;
          buildTree(node * 2, lo, m);
          buildTree(node * 2 + 1, m + 1, hi);
          pushUp(node, lo, hi);
      }

      private void pushUp(int node, int lo, int hi)
      {
          if (lo >= hi) return;

          // note that, if we need to call pushUp on a node, then lazy[node] must be zero.

          //the true value is the value + lazy
          treeMin[node] = Math.min(treeMin[node * 2] + lazy[node * 2], treeMin[node * 2 + 1] + lazy[node * 2 + 1]);
          treeMax[node] = Math.max(treeMax[node * 2] + lazy[node * 2], treeMax[node * 2 + 1] + lazy[node * 2 + 1]);
          // add combine fcn
      }

      private void pushDown(int node, int lo, int hi)
      {
          if (lazy[node] == 0) return;

          int lz = lazy[node];
          lazy[node] = 0;

          treeMin[node] += lz;
          treeMax[node] += lz;

          if (lo == hi) return;

          int mid = (lo + hi) / 2;
          lazy[node * 2] += lz;
          lazy[node * 2 + 1] += lz;
      }

      public int rangeQueryMax(int fr, int to)
      {
          return rangeQueryMax(1, 0, n-1, fr, to);
      }

      public int rangeQueryMax(int node, int lo, int hi, int fr, int to)
      {
          if (lo == fr && hi == to)
              return treeMax[node] + lazy[node];

          int mid = (lo + hi) / 2;
          pushDown(node, lo, hi);

          if (to <= mid) {
              return rangeQueryMax(node * 2, lo, mid, fr, to);
          }else if (fr > mid)
              return rangeQueryMax(node * 2 + 1, mid + 1, hi, fr, to);
          else {
              return Math.max(rangeQueryMax(node * 2, lo, mid, fr, mid),
                              rangeQueryMax(node * 2 + 1, mid + 1, hi, mid + 1, to));
          }
      }

      public int rangeQueryMin(int fr, int to)
      {
          return rangeQueryMin(1, 0, n-1, fr, to);
      }

      public int rangeQueryMin(int node, int lo, int hi, int fr, int to)
      {
          if (lo == fr && hi == to)
              return treeMin[node] + lazy[node];

          int mid = (lo + hi) / 2;
          pushDown(node, lo, hi);

          if (to <= mid) {
              return rangeQueryMin(node * 2, lo, mid, fr, to);
          }else if (fr > mid)
              return rangeQueryMin(node * 2 + 1, mid + 1, hi, fr, to);
          else {
              return Math.min(rangeQueryMin(node * 2, lo, mid, fr, mid),
                              rangeQueryMin(node * 2 + 1, mid + 1, hi, mid + 1, to));
          }
      }

       public void rangeUpdate(int fr, int to, int delta){
           rangeUpdate(1, 0, n-1, fr, to, delta);
       }

      public void rangeUpdate(int node, int lo, int hi, int fr, int to, int delta){
          pushDown(node, lo, hi);
          if (fr == lo && to == hi)
          {
              lazy[node] = delta;
              return;
          }

          int m = (lo + hi) / 2;
          if (to <= m)
              rangeUpdate(node * 2, lo, m, fr, to, delta);
          else if (fr > m)
              rangeUpdate(node * 2 + 1, m + 1, hi, fr, to, delta);
          else  {
              rangeUpdate(node *  2, lo, m, fr, m, delta);
              rangeUpdate(node * 2 + 1, m + 1, hi, m + 1, to, delta);
          }

          // re-set the in-variant
          pushUp(node, lo, hi);
      }

      public int query(int node, int lo, int hi, int fr, int to)
      {
          if (fr == lo && to == hi)
              return tree[node];

          int m = (lo + hi) / 2;
          if (to <= m)
              return  query(node * 2, lo, m, fr, to);
          else if (fr > m)
              return query(node * 2 + 1, m + 1, hi, fr, to);

          int lid = query(node * 2, lo, m, fr, m);
          int rid = query(node * 2 + 1, m + 1, hi, m + 1, to);
          return a[lid] >= a[rid] ? lid : rid;
      }

  }

  private long inv(long v)
  {
      return pow(v, MOD-2);
  }

  private long pow(long v, long p)
  {
      long ans = 1;
      while (p > 0)
      {
          if (p % 2 == 1)
              ans = ans * v % MOD;
          v = v * v % MOD;
          p = p / 2;
      }
      return ans;
  }

  private double dist(double x, double y, double xx, double yy)
  {
      return Math.sqrt((xx - x) * (xx - x) + (yy - y) * (yy - y));
  }

  private int mod_add(int a, int b) {
      int v = a + b;
      if (v >= MOD) v -= MOD;
      return v;
  }

  private long overlap(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4) {
      if (x1 > x3) return overlap(x3, y3, x4, y4, x1, y1, x2, y2);

      if (x3 > x2 || y4 < y1 || y3 > y2) return 0L;

      //(x3, ?, x2, ?)
      int yL = Math.max(y1, y3);
      int yH = Math.min(y2, y4);
      int xH = Math.min(x2, x4);

      return f(x3, yL, xH, yH);
  }
  //return #black cells in rectangle
  private long f(int x1, int y1, int x2, int y2) {
      long dx = 1L + x2 - x1;
      long dy = 1L + y2 - y1;
      if (dx % 2 == 0 || dy % 2 == 0 || (x1 + y1) % 2 == 0)
          return 1L * dx * dy / 2;
      return 1L * dx * dy / 2 + 1;
  }

  private int distM(int x, int y, int xx, int yy) {
      return abs(x - xx) + abs(y - yy);
  }

  private boolean less(int x, int y, int xx, int yy) {
      return x < xx || y > yy;
  }

  private int mul(int x, int y) {
      return (int)(1L * x * y % MOD);
  }

  private int nBit1(int v) {
      int v0 = v;
      int c = 0;
      while (v != 0) {
          ++c;
          v = v & (v - 1);
      }
      return c;
  }

  private long abs(long v) {
      return v > 0 ? v : -v;
  }

  private int abs(int v) {
      return v > 0 ? v : -v;
  }

  private int common(int v) {
      int c = 0;
      while (v != 1) {
          v = (v >>> 1);
          ++c;
      }

      return c;
  }

  private void reverse(char[] a, int i, int j) {
      while (i < j) {
          swap(a, i++, j--);
      }
  }

  private void swap(char[] a, int i, int j) {
      char t = a[i];
      a[i] = a[j];
      a[j] = t;
  }

  private int gcd(int x, int y) {
      if (y == 0) return x;
      return gcd(y, x % y);
  }
  private long gcd(long x, long y) {
      if (y == 0) return x;
      return gcd(y, x % y);
  }
  private int max(int a, int b) {
      return a >  b ? a : b;
  }

  private long max(long a, long b) {
      return a >  b ? a : b;
  }

  private int min(int a, int b) {
      return a >  b ? b : a;
  }

  private long min(long a, long b) {
      return a >  b ? b : a;
  }

  static class FastReader
    {
        BufferedReader br;
        StringTokenizer st;

        public FastReader(BufferedReader in)
        {
            br = in;
        }

        String next()
        {
            while (st == null || !st.hasMoreElements())
            {
                try
                {
                    String line = br.readLine();
                    if (line == null || line.length() == 0) return "";
                    st = new StringTokenizer(line);
                }
                catch (IOException  e)
                {
                    return "";
                    //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)
            {
                return null;
                //e.printStackTrace();
            }
            return str;
        }
    }
}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.List;
import java.util.Scanner;
import java.util.Set;
import java.util.Collections;
import java.util.TreeSet;
import java.util.ArrayList;

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

    static class TaskE {
        List<Integer> solve(int[] a, int s, int e) {
            Set<Integer> foo = new TreeSet<>();
            foo.add(0);
            for (int i = s; i < e; ++i) {
                Set<Integer> tmp = new HashSet<>();
                for (int val : foo) {
                    if (!foo.contains(val + a[i])) {
                        tmp.add(val + a[i]);
                    }
                }
                for (int val : tmp) {
                    foo.add(val);
                }
            }

            List<Integer> res = new ArrayList<>();
            res.addAll(foo);

            return res;
        }

        public void solve(int testNumber, Scanner in, PrintWriter out) {
            int n = in.nextInt(), m = in.nextInt();

            int[] a = new int[n];
            for (int i = 0; i < n; ++i) {
                a[i] = in.nextInt();
                a[i] %= m;
            }
            List<Integer> left = solve(a, 0, n / 2);
            List<Integer> right = solve(a, n / 2, n);

            int res = 0;
            for (int i : left) {
                int tmp = Collections.binarySearch(right, m - 1 - i);

                if (tmp >= 0) {
                    res = m - 1;
                    break;
                } else {
                    tmp = -tmp - 2;
                    res = Math.max(res, i + right.get(tmp));
                }
            }

            out.println(res);
        }

    }
}


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

public class MaximumSubsequence
{
	static boolean[] setChecker(int[] A,int m)
	{
		boolean[] M = new boolean[m] ;
		int set_size = A.length ;
		int power_set_size = (int)Math.pow(2,set_size) ;
		for(int i=0;i<power_set_size;i++)
		{
			int sum = 0 ;
			for(int j=0;j<set_size;j++)
			{
				if((i & (1<<j))!=0)
					sum = sum + A[j] ;
			}
			M[(sum%m)] = true ;
		}
		return M ;
	}
	static void arrayPrinter(int[] A)
	{
		for(int i=0;i<A.length;i++)
		{
			System.out.print(A[i]+" ") ;
		}
	}
	static int maxPossibleValue(int[] A,int m)
	{
		if(m==1)
			return 0 ;
		int half_length = A.length/2 ;
		int[] first_half = new int[half_length] ;
		int[] second_half  = new int[A.length-half_length] ;

		for(int i=0;i<half_length;i++)
		{
			first_half[i] = A[i] ;
		}
		for(int i=half_length;i<second_half.length+half_length;i++)
		{
			second_half[i-half_length] = A[i] ;
		}
		// System.out.println("first_half") ;
		// arrayPrinter(first_half) ;
		// System.out.println("\nsecond_half") ;
		// arrayPrinter(second_half) ;
		// System.out.println("A:") ;
		// arrayPrinter(A) ;
		boolean[] M1 = setChecker(first_half,m) ;
		boolean[] M2 = setChecker(second_half,m) ;
		// for(int i=0;i<M1.length;i++)
		// {
			// if(M1[i])
				// System.out.println(i) ;
		// }
		// System.out.println() ;
		// for(int i=0;i<M2.length;i++)
		// {
			// if(M2[i])
				// System.out.println(i) ;
		// }
		// System.out.println() ;
		int maxPV = 0 ;
		for(int i=0;i<m;i++)
		{
			if(M1[i])
			{
				for(int j=0;j<m;j++)
				{
					if(M2[j])
					{
						if((i+j)%m>maxPV)
							maxPV = (i+j)%m ;
					}
				}
			}
		}
		return maxPV ;
	}
	public static void main(String args[]) throws Exception
	{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in)) ;
		String line1 = br.readLine() ;
		String line2 = br.readLine() ;
		int size = Integer.parseInt(line1.split(" ")[0]) ;
		int m = Integer.parseInt(line1.split(" ")[1]) ;
		int[] A = new int[size] ;
		for(int i=0;i<size;i++)
		{
			A[i] = Integer.parseInt(line2.split(" ")[i]) ;
		}
		System.out.println(maxPossibleValue(A,m)) ;

	}
}


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

public class MaximumSubsequence
{
	static long pow(long n,long p)
	{
		long  result = 1;
		if(p==0)
		   return 1;
		if (p==1)
		    return n;
		while(p!=0)
		{
		    if(p%2==1)
		        result *= n;
		    p >>=1;
		    n*=n;
		}
		return result;
	}
	static HashSet<Integer> setChecker(int[] A,int m)
	{
		// boolean[] M = new boolean[m] ;
		HashSet<Integer> H = new HashSet<Integer>() ;
		int set_size = A.length ;
		int power_set_size = (int)pow(2,set_size) ;
		for(int i=0;i<power_set_size;i++)
		{
			int sum = 0 ;
			for(int j=0;j<set_size;j++)
			{
				if((i & (1<<j))!=0)
					sum = sum + A[j] ;
			}
			H.add((sum%m)) ;
		}
		return H ;
	}
	static void arrayPrinter(int[] A)
	{
		for(int i=0;i<A.length;i++)
		{
			System.out.print(A[i]+" ") ;
		}
		System.out.println() ;
	}
	static int maxPossibleValue(int[] A,int m)
	{
		if(m==1)
			return 0 ;
		int half_length = A.length/2 ;
		int[] first_half = new int[half_length] ;
		int[] second_half  = new int[A.length-half_length] ;

		for(int i=0;i<half_length;i++)
		{
			first_half[i] = A[i] ;
		}
		for(int i=half_length;i<second_half.length+half_length;i++)
		{
			second_half[i-half_length] = A[i] ;
		}
		// System.out.println("first_half") ;
		// arrayPrinter(first_half) ;
		// System.out.println("\nsecond_half") ;
		// arrayPrinter(second_half) ;
		// System.out.println("A:") ;
		// arrayPrinter(A) ;
		HashSet<Integer> H1 = setChecker(first_half,m) ;
		HashSet<Integer> H2  = setChecker(second_half,m) ;
		Integer[] A1 = H1.toArray(new Integer[H1.size()]) ;
		Integer[] A2 = H2.toArray(new Integer[H2.size()]) ;

		// Iterator I1 = H1.iterator() ;
		// Iterator I2 = H2.iterator() ;
		// System.out.println("H1:") ;
		int maxPV = 0 ;
		for(int i=0;i<A1.length;i++)
		{
			for(int j=0;j<A2.length;j++)
			{
				if((A1[i]+A2[j])%m > maxPV)
					maxPV = (A1[i]+A2[j])%m ;
			}
		}
		System.out.println() ;
		// while(I1.hasNext())
		// {
			// int i = I1.next() ;
			// while(I2.hasNext)
			// {
				// int j = I2.next() ;
				// if((i+j)%m>maxPV)
					// maxPV = (i+j)%m ;
			// }
		// }
		// System.out.println(maxPV) ;
		// System.out.println("\nH2:") ;
		// while(I2.hasNext())
		// {
			// System.out.print(I2.next()+" ") ;
		// }
		// for(int i=0;i<M1.length;i++)
		// {
			// if(M1[i])
				// System.out.println(i) ;
		// }
		// System.out.println() ;
		// for(int i=0;i<M2.length;i++)
		// {
			// if(M2[i])
				// System.out.println(i) ;
		// }
		// System.out.println() ;

		// for(int i=0;i<m;i++)
		// {
			// if(M1[i])
			// {
				// for(int j=0;j<m;j++)
				// {
					// if(M2[j])
					// {
						// if((i+j)%m>maxPV)
							// maxPV = (i+j)%m ;
					// }
				// }
			// }
		// }

		return maxPV ;
	}
	public static void main(String args[]) throws Exception
	{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in)) ;
		String line1 = br.readLine() ;
		String line2 = br.readLine() ;
		int size = Integer.parseInt(line1.split(" ")[0]) ;
		int m = Integer.parseInt(line1.split(" ")[1]) ;
		int[] A = new int[size] ;
		for(int i=0;i<size;i++)
		{
			A[i] = Integer.parseInt(line2.split(" ")[i]) ;
		}
		System.out.println(maxPossibleValue(A,m)) ;

	}
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by mohannadhassan on 8/18/17.
 */
public class GenerousKefa {

    public static void main(String [] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        String[] input = br.readLine().split(" ");

        int baloonsCnt = Integer.parseInt(input[0]);
        int friendsCnt = Integer.parseInt(input[1]);

        String baloons = br.readLine();

        HashMap<Character, Integer> charsCount = new HashMap<>();

        for (char c: baloons.toCharArray()) {
            Integer count = charsCount.get(c);
            if (count == null) {
                count = 0;
            }
            charsCount.put(c, count + 1);
        }

        boolean valid = true;
        for (Map.Entry<Character, Integer> c :
                charsCount.entrySet()) {
            if (c.getValue() < friendsCnt) {
                valid = false;
                break;
            }
        }
        System.out.println(valid ? "YES" : "NO");
    }
}


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Random;
import java.util.Scanner;
import java.io.*;

public class Main {
	public static void main(String[] args) throws FileNotFoundException {
		// Scanner read = new Scanner(new FileInputStream(new
		// File("input.txt")));
		// PrintWriter out = new PrintWriter(new File("output.txt"));
		Scanner read = new Scanner(System.in);
		int n = read.nextInt(), k = read.nextInt(), arr[] = new int[26];
		String s = read.next();
		read.nextLine();
		for (int i = 0; i < n; i++)
			arr[s.charAt(i) - 97]++;
		boolean check = true;

			for (int i = 0; i < 26; i++) {
				if (arr[i] >= k) {
					check = false;
					System.out.println("NO");
					break;
				}
			}

		if (check)
			System.out.println("YES");

	}
}


import java.util.Scanner;

public class ballons4 {
public static void main (String[] args){
	//int nb=7;
	//int nf=2;
	//String s="ovovm";
	Scanner input=new Scanner(System.in);
	int nb=input.nextInt();
	int	nf=input.nextInt();
	String s=input.next();

	char[] charsu = new char[nb];
	long[] numsu = new long[nb];
	int num=0;
	//int k=0;
	for (int i=0; i<nb; i++){
		int found=-1;
		for(int j=0;j<num;j++){
		if(s.charAt(i)==charsu[j]){
			found=1;
			numsu[j]++;
		}
		}
		if(found==-1){
			charsu[num]=s.charAt(i);
			numsu[num]=1;
			//num++;
		}

	}

	for (int i=0; i<nb;i++){
		if (numsu[i]>nf){
			System.out.println( "NO");
				return;
		}

	}
	 System.out.println ("YES");

}
}


import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class BetweenOffices {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int t = sc.nextInt();
		int count = 0;
		int count1=0;
		for (int i=0;i<t;i++) {
		String s = sc.next();
		Pattern pattern = Pattern.compile("SF");
		Pattern pattern1 = Pattern.compile("FS");
		Matcher m = pattern.matcher(s);
		Matcher m1 = pattern1.matcher(s);
		while (m.find()) {
			count++;
		}
		while (m1.find()) {
			count1++;
		}

		if (count>count1) {
			System.out.println("YES");
		}
		else {
			System.out.println("NO");
		}
		}
	}
}


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

public class Main {
    static int MOD = (int)1e9 + 7;

    public void run() {
        try {
            int n = reader.nextInt();
            int m = reader.nextInt();
            int[] pow = new int[n + 1];
            pow[0] = 1;
            for (int i = 1; i <= n; ++ i) {
                pow[i] = (pow[i - 1] << 1) % MOD;
            }
            int[][] ways = new int[m + 1][1];
            ways[0][0] = 1;
            for (int i = 0; i < n; ++ i) {
                int[][] newWays = new int[m + 1][i + 2];
                for (int maximum = 0; maximum <= m; ++ maximum) {
                    for (int last = 0; last <= i; ++ last) {
                        newWays[maximum][last] = add(newWays[maximum][last], ways[maximum][last]);
                        newWays[maximum][last] = add(newWays[maximum][last], (int)(ways[maximum][last] * (pow[last] - 1) % MOD));
                        if (maximum + 1 <= m) {
                            newWays[maximum + 1][i + 1] = add(newWays[maximum + 1][i + 1], (int)(ways[maximum][last] * (pow[i + 1] - pow[last]) % MOD));
                        }
                    }
                }
                ways = newWays;
            }
            int result = 0;
            for (int last = 0; last <= n; ++ last) {
                result = add(result, ways[m][last]);
            }
            writer.println(result);
        } catch (IOException ex) {
        }
        writer.close();
    }

    int add(int x, int a) {
        if (a < 0) {
            a += MOD;
        }
        x += a;
        if (x >= MOD) {
            x -= MOD;
        }
        return x;
    }

    Main() {
        reader = new InputReader(System.in);
        writer = new PrintWriter(System.out);
    }

    public static void main(String[] args) {
        new Main().run();
    }

    private void debug(Object...os) {
        System.err.println(Arrays.deepToString(os));
    }

    private InputReader reader;
    private PrintWriter writer;
}

class InputReader {
    InputReader(InputStream in) {
        reader    = new BufferedReader(new InputStreamReader(in));
        tokenizer = new StringTokenizer("");
    }

    private String next() throws IOException {
        while (!tokenizer.hasMoreTokens()) {
            tokenizer = new StringTokenizer(reader.readLine());
        }
        return tokenizer.nextToken();
    }

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

    private BufferedReader  reader;
    private StringTokenizer tokenizer;
}


import java.awt.*;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        int m = scan.nextInt();
        int[][] arr = new int[n][m];
        int num = 0;
        for (int i=0;i<n;i++){
            for (int j=0;j<m;j++){
                arr[i][j]=scan.nextInt();
            }
        }
        for (int i=0;i<n;i++){
            for (int j=0;j<m-1;j++){
               if (arr[i][j]==arr[i][j+1]){
                    arr[i][j]=0;
                    arr[i][j+1]=0;
                }
            }
        }
        for (int i=0;i<n-1;i++){
            for (int j=0;j<m;j++){
                if (arr[i][j]==arr[i+1][j]){
                    arr[i][j]=0;
                    arr[i+1][j]=0;
                }
            }
        }
        for (int i=0;i<n;i++){
            for (int j=0;j<m;j++){
                if (arr[i][j]!=0){
                    num +=1;
                }
            }
        }

        int single = getSingle(n,m,arr);
        num = num/2+single;
        System.out.println(num);

    }

    private static int getSingle(int n, int m, int[][] arr) {
        int num=0;
        for (int i=0;i<n;i++){
            for (int j=0;j<m-1;j++){
                if (arr[i][j]!=0&&arr[i][j+1]!=0){
                    arr[i][j]=-1;
                    arr[i][j+1]=-1;
                }
            }
        }
        for (int i=0;i<n-1;i++){
            for (int j=0;j<m;j++){
                if (arr[i][j]!=0&&arr[i+1][j]!=0){
                    arr[i][j]=-1;
                    arr[i+1][j]=-1;
                }
            }
        }
        ArrayList<Point> list = new ArrayList();
        for (int i=0;i<n;i++){
            for (int j=0;j<m;j++){
                if (arr[i][j]!=0&&arr[i][j]!=-1){
                    Point p = new Point(i,j);
                    list.add(p);
                    num +=1;
                }
            }
        }
        int temp =0;
        for (int i=0;i< list.size()-1;i++){
            for (int j=i+1;j< list.size();j++){
                Point p1 = list.get(i);
                Point p2 = list.get(j);
                if (Math.abs(p1.x-p2.x)==2&&Math.abs(p1.y-p2.y)==1||Math.abs(p1.x-p2.x)==1&&Math.abs(p1.y-p2.y)==2){
                    temp+=1;
                    list.remove(i);
                    list.remove(j);
                    break;
                }
            }

        }
        num=num-temp;
        return num;
    }
}


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

public class C {

    int n, m, k;
    int[][] f;
    int[][] c;
    boolean[] mask;
    int best = Integer.MAX_VALUE;

    void calc(int i, int j, int cnt) {
        if (cnt < best) {
            if (i == n - 1 && j == m) {
                best = cnt;
            } else {
                if (j == m) {
                    j = 0;
                    ++i;
                }
                if (c[i][j] > 0) {
                    calc(i, j + 1, cnt);
                } else {
                    for (int r = 1; r <= k; ++r) {
                        if (!mask[r - 1]) {
                            c[i][j] = r;
                            mask[r - 1] = true;
                            if (j < m - 1) {
                                c[i][j + 1] = r;
                                int d = 0;
                                if (c[i][j] != f[i][j]) ++d;
                                if (c[i][j + 1] != f[i][j + 1]) ++d;
                                calc(i, j + 2, cnt + d);
                                c[i][j + 1] = 0;
                            }
                            if (i < n - 1) {
                                c[i + 1][j] = r;
                                int d = 0;
                                if (c[i][j] != f[i][j]) ++d;
                                if (c[i + 1][j] != f[i + 1][j]) ++d;
                                calc(i, j + 1, cnt + d);
                                c[i + 1][j] = 0;
                            }
                            mask[r - 1] = false;
                        }
                    }
                    c[i][j] = 0;
                }
            }
        }
    }

    void solve() throws IOException {
        in("__std"); out("__std");

        n = readInt();
        m = readInt();
        k = n * m / 2;
        f = new int[n][m];
        c = new int[n][m];
        mask = new boolean[k];
        for (int i = 0; i < n; ++i) {
            for (int j  = 0; j < m; ++j) {
                f[i][j] = readInt();
            }
        }
        calc(0, 0, 0);
        println(best);

        exit();
    }

    void in(String name) throws IOException {
        if (name.equals("__std")) {
            in = new BufferedReader(new InputStreamReader(System.in));
        } else {
            in = new BufferedReader(new FileReader(name));
        }
    }

    void out(String name) throws IOException {
        if (name.equals("__std")) {
            out = new PrintWriter(System.out);
        } else {
            out = new PrintWriter(name);
        }
    }

    void exit() {
        out.close();
        System.exit(0);
    }

    char readChar() throws IOException {
        return (char) in.read();
    }

    int readInt() throws IOException {
        return Integer.parseInt(readToken());
    }

    long readLong() throws IOException {
        return Long.parseLong(readToken());
    }

    double readDouble() throws IOException {
        return Double.parseDouble(readToken());
    }

    String readLine() throws IOException {
        st = null;
        return in.readLine();
    }

    String readToken() throws IOException {
        while (st == null || !st.hasMoreTokens()) {
            st = new StringTokenizer(in.readLine());
        }
        return st.nextToken();
    }

    boolean eof() throws IOException {
        return !in.ready();
    }

    void print(String format, Object ... args) {
        out.print(new Formatter(Locale.US).format(format, args));
    }

    void println(String format, Object ... args) {
        out.println(new Formatter(Locale.US).format(format, args));
    }

    void print(Object value) {
        out.print(value);
    }

    void println(Object value) {
        out.println(value);
    }

    void println() {
        out.println();
    }

    StringTokenizer st;

    BufferedReader in;
    PrintWriter out;

    public static void main(String[] args) throws IOException {
        new C().solve();
    }
}


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

public class C1 {

    int n, m, k;
    int[][] f;
    boolean[][] c;
    boolean[] mask;
    int best = Integer.MAX_VALUE;

    void calc(int i, int j, int cnt) {
        if (cnt < best) {
            if (i == n - 1 && j == m) {
                best = cnt;
            } else {
                if (j == m) {
                    j = 0;
                    ++i;
                }
                if (c[i][j]) {
                    calc(i, j + 1, cnt);
                } else {
                    for (int r = 1; r <= k; ++r) {
                        if (!mask[r - 1]) {
                            mask[r - 1] = true;
                            c[i][j] = true;
                            if (j < m - 1 && !c[i][j + 1]) {
                                c[i][j + 1] = true;
                                int d = 0;
                                if (r != f[i][j]) ++d;
                                if (r != f[i][j + 1]) ++d;
                                calc(i, j + 1, cnt + d);
                                c[i][j + 1] = false;
                            }
                            if (i < n - 1) {
                                c[i + 1][j] = true;
                                int d = 0;
                                if (r != f[i][j]) ++d;
                                if (r != f[i + 1][j]) ++d;
                                calc(i, j + 1, cnt + d);
                                c[i + 1][j] = false;
                            }
                            mask[r - 1] = false;
                            c[i][j] = false;
                        }
                    }
                }
            }
        }
    }

    void solve() throws IOException {
        in("__std"); out("__std");

        n = readInt();
        m = readInt();
        k = n * m / 2;
        f = new int[n][m];
        c = new boolean[n][m];
        mask = new boolean[k];
        for (int i = 0; i < n; ++i) {
            for (int j  = 0; j < m; ++j) {
                f[i][j] = readInt();
            }
        }
        calc(0, 0, 0);
        println(best);

        exit();
    }

    void in(String name) throws IOException {
        if (name.equals("__std")) {
            in = new BufferedReader(new InputStreamReader(System.in));
        } else {
            in = new BufferedReader(new FileReader(name));
        }
    }

    void out(String name) throws IOException {
        if (name.equals("__std")) {
            out = new PrintWriter(System.out);
        } else {
            out = new PrintWriter(name);
        }
    }

    void exit() {
        out.close();
        System.exit(0);
    }

    char readChar() throws IOException {
        return (char) in.read();
    }

    int readInt() throws IOException {
        return Integer.parseInt(readToken());
    }

    long readLong() throws IOException {
        return Long.parseLong(readToken());
    }

    double readDouble() throws IOException {
        return Double.parseDouble(readToken());
    }

    String readLine() throws IOException {
        st = null;
        return in.readLine();
    }

    String readToken() throws IOException {
        while (st == null || !st.hasMoreTokens()) {
            st = new StringTokenizer(in.readLine());
        }
        return st.nextToken();
    }

    boolean eof() throws IOException {
        return !in.ready();
    }

    void print(String format, Object ... args) {
        out.print(new Formatter(Locale.US).format(format, args));
    }

    void println(String format, Object ... args) {
        out.println(new Formatter(Locale.US).format(format, args));
    }

    void print(Object value) {
        out.print(value);
    }

    void println(Object value) {
        out.println(value);
    }

    void println() {
        out.println();
    }

    StringTokenizer st;

    BufferedReader in;
    PrintWriter out;

    public static void main(String[] args) throws IOException {
        new C1().solve();
    }
}


/*
 * Code Author: Jayesh Udhani
 * Dhirubhai Ambani Institute of Information and Communication Technology (DA-IICT ,Gandhinagar)
 * 2nd Year ICT BTECH Student
 */
import java.io.*;
import java.util.*;

public class Main {
	public static void main(String args[])
	{
		InputReader in = new InputReader(System.in);
		OutputStream outputStream = System.out;
		PrintWriter out = new PrintWriter(outputStream);
		//----------My Code Starts Here----------
		int n=in.nextInt(),i,ans=0;
		int t=0;
		int[] arr=new int[n];
		int s=(int) (1e9+1);
		int[] ctr=new int[s];
		Arrays.fill(ctr, 0);
		for(i=0;i<n;i++)
		{
			arr[i]=in.nextInt();
			ctr[arr[i]]++;
		}
		for(i=0;i<n;i++)
		{
			t=0;
			if(ctr[arr[i]]==1)
				ans++;
			else if(ctr[arr[i]]>1)
			{
				ans++;
				int x=arr[i],index=arr[i];
				while(ctr[x]!=1)
				{
	/*				while(ctr[y]!=0)
					{
						if(y==0)
						{
							ctr[x]=0;
							t=1;
							break;
						}
						y--;
					}
					if(t==0)
					{
						ctr[y]++;
						ctr[x]--;
					}
					else
						break;*/
					index--;
					if(index==0)
					{
						ctr[x]=0;
						t=1;
						break;
					}
					if(ctr[index]==0)
					{
						ctr[index]++;
						ctr[x]--;
						ans++;
					}
				}
			}
		}
		out.println(ans);
		out.close();
		//---------------The End———————————————————
	}
	static class InputReader {
		public BufferedReader reader;
		public StringTokenizer tokenizer;

		public InputReader(InputStream inputstream) {
			reader = new BufferedReader(new InputStreamReader(inputstream));
			tokenizer = null;
		}

		public String nextLine(){
			String fullLine=null;
			while (tokenizer == null || !tokenizer.hasMoreTokens()) {
				try {
					fullLine=reader.readLine();
				} catch (IOException e) {
					throw new RuntimeException(e);
				}
				return fullLine;
			}
			return fullLine;
		}
		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 long nextLong() {
			return Long.parseLong(next());
		}
		public int nextInt() {
			return Integer.parseInt(next());
		}
	}
}


public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        sc.close();

        String s = Integer.toString(n);
        int l = 0, r = s.length()-1;
        while (l < s.length()-1 && s.charAt(l) == '0') {
            l++;
        }
        while (r >= 0 && s.charAt(r) == '0') {
            r--;
        }

        while (l < r) {
            if (s.charAt(l++) != s.charAt(r--)) {
                System.out.println("NO");
                return;
            }
        }
        System.out.println("YES");
        return;
    }
}


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

public class Solution{
	public static String reducedNumber(int number){
		while((number%10)==0){
			number = number/10;
		}
		return number.toString();
	}
	public static void quasiPalindrome(String s){
		String rev_s = new StringBuilder(s).reverse().toString();
		if(s.equals(rev_s))
			System.out.println("YES");
		else
			System.out.println("NO");
	}
	public static void main(String args[]){
		int x;
		String temp;
		Scanner s = new Scanner(System.in);
		x = s.nextInt();
		s.close();
		temp = reducedNumber(x);
		quasiPalindrome(temp);
	}
}


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

public class Main {
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		PrintWriter out = new PrintWriter(System.out);

		Task solver = new Task();
		solver.solve(in, out);
		out.close();
	}
}

class Task {
	final static int MAXN = 211111;
	final static long MD = 1000000007;
	long[] inv, fact, factInv;

	long pow(int x, int y) {
		long ret = 1, tmp = x;
		for (; y > 0; y >>= 1) {
			if ((y & 1) == 1)
				ret = ret * tmp % MD;
			tmp = tmp * tmp % MD;
		}
		return ret;
	}

	long perm(int n, int m) {
		return n < m ? 0 : fact[n] * factInv[n - m] % MD;
	}

	void solve(Scanner in, PrintWriter out) {
		int k = in.nextInt(), w = in.nextInt();
		inv = new long[MAXN];
		fact = new long[MAXN];
		factInv = new long[MAXN];
		inv[1] = 1;
		for (int i = 2; i < MAXN; ++i)
			inv[i] = (MD - MD / i * inv[(int)MD % i] % MD) % MD;

		fact[0] = factInv[0] = 1;
		for (int i = 1; i < MAXN; ++i) {
			fact[i] = fact[i - 1] * i % MD;
			factInv[i] = factInv[i - 1] * inv[i] % MD;
		}

		long ans = 0;
		for (int t = 1; t <= k; ++t) {
			if (w - 1 >= t)
				ans = (ans + perm(k, t) * perm(k, t) % MD * t % MD * pow(k, w - 1 - t) % MD) % MD;
			else
				ans = (ans + perm(k, t) * perm(k - t + w - 1, w - 1) % MD * w % MD) % MD;
			if (w - 1 >= t + 1)
				ans = (ans + perm(k, t) * perm(k, t + 1) % MD * t % MD * pow(k, w - 2 - t) % MD) % MD;
			else
				ans = (ans + perm(k, t) * perm(k - 2 - t + w, w - 1) % MD * (w - 1) % MD) % MD;
		}

		out.println(ans);
	}
}


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

public class Main
{
    static int MOD = 1000000007;
    static long dfac[],fac[];

    public static int A(int n,int r)
    {
        return (int)((long)fac[n] * quickPow((int)fac[n-r],MOD-2) % MOD);
    }

    public static int quickPow(int x,int n)
    {
        long ans = 1;
        for (;n != 0;n >>= 1)
        {
            if ((n & 1) != 0) ans = ans * x % MOD;
            x = (int)((long) x * (long) x % MOD);
        }
        return (int)ans;
    }

    public static int eat(int len,int k,int w)
    {
        long ret = A(k,len);
        int delta = len - (w - 1);
        if (delta >= 0)
        {
            ret = ret * A(k-delta,len-delta) % MOD;
        }
        else
        {
            ret = ret * A(k,len) % MOD;
            ret = ret * quickPow(k,w-1-len) % MOD;
        }
        return (int)ret;
    }

    public static int fuck(int k,int w,boolean inclusive)
    {
        long ret = 0;
        for (int i = inclusive ? 1 : 2;i <= k;++i)
            ret = (ret + eat(i,k,w)) % MOD;
        return (int)ret;
    }

    public static int gao(int k,int w)
    {
        fac = new long[k+1];
        fac[0] = 1;
        for (int i = 1;i <= k;++i)
            fac[i] = fac[i-1] * i % MOD;
        return ( (fuck(k,w+1,true) - fuck(k,w,false) ) % MOD + MOD) % MOD;
    }

    public static void main(String args[])
    {
        Scanner cin = new Scanner(System.in);
        int k = cin.nextInt(), w = cin.nextInt();
        System.out.println(gao(k,w));
    }
}


//package round97;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;

public class E2 {
	InputStream is;
	PrintWriter out;
	String INPUT = "";
//	String INPUT = "2 139";
//	String INPUT = "2 139";
	int mod = 1000000007;

	long[] PS = new long[1000001];
	long[] IPS = new long[1000001];
	long[] KE = new long[1000002];
	long[] KE2 = new long[1000020];

	void solve()
	{
		int k = ni(), w = ni();
		long sum = 0;
		PS[0] = 1;
		IPS[0] = 1;
		KE[0] = modpow(k, w, mod);
		KE2[0] = modpow(k, w+4, mod);
		long ik = inv(k, mod);
		for(int i = 1;i <= k;i++){
			PS[i] = PS[i-1]*(k-i+1)%mod;
			IPS[i] = IPS[i-1]*inv(k-i+1, mod)%mod;
			KE[i] = KE[i-1] * k % mod;
		}
		for(int i = 1;i <= k+19;i++){
			KE2[i] = KE2[i-1] * ik % mod;
		}
		gw = w;
		for(int l = w+1;l <= w+k;l++){
			long v = (val(k, w, l) - val(k, w+1, l)) % mod;
			sum += v;
//			tr(l, v);
		}
		out.println((sum%mod+mod)%mod);
	}

	public static long inv(long a, int p)
	{
		long ret = 1;
		long mul = a;
		for(long n = p-2;n > 0;n >>>= 1){
			if((n&1)==1)ret = ret * mul % p;
			mul = mul * mul % p;
		}
		return ret;
	}

	int gw;

	// k=2,W=2,L=3
	// 8

	int gct = 0;
	//
	// OXO
	long val(long k, long W, long L)
	{
		if(W >= L)return 0;
		// headで含む
		// tailで含む
		// 2W-L+2=W+2-(L-W)
		long ret;
		if(W > L+1-W){
//			ret = modpow(k, L, mod) - modpow(k, L-2*(L-W+1), mod) * modpow(P(k, L-W+1), 2, mod)%mod;
			ret = KE[(int)(L-gw)] - KE2[(int)(gw+4-(L-2*(L-W+1)))] * modpow(P(k, L-W+1), 2, mod)%mod;
		}else{
//			long p = k-(L-2*(W-1)) < W-1 ? 0 : P(k, W-1)*inv(P(k, L-2*(W-1)), mod)%mod;
			long p = k-(L-2*(W-1)) < W-1 ? 0 : P(k, W-1)*invP(k, L-2*(W-1))%mod;
//			ret = modpow(k, L, mod) - P(k,L-2*(W-1))*modpow(p, 2, mod)%mod;
			ret = KE[(int)(L-gw)] - P(k,L-2*(W-1))*modpow(p, 2, mod)%mod;
		}

		return (int)((ret%mod+mod)%mod);
	}

	long P(long n, long r)
	{
		if(r > n)return 0;
		return PS[(int)r];
	}

	long invP(long n, long r)
	{
		if(r > n)return 0;
		return IPS[(int)r];
	}

	public static long modpow(long a, long n, long mod)
	{
		long ret = 1;
		long mul = a;
		for(;n > 0;n >>>= 1){
			if((n&1)==1){
				ret = (ret * mul) % mod;
			}
			mul = (mul * mul) % mod;
		}
		return ret;
	}

	void run() throws Exception
	{
		is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
		out = new PrintWriter(System.out);

		long s = System.currentTimeMillis();
		solve();
		out.flush();
		tr(System.currentTimeMillis()-s+"ms");
	}

	public static void main(String[] args) throws Exception
	{
		new E2().run();
	}

	public int ni()
	{
		try {
			int num = 0;
			boolean minus = false;
			while((num = is.read()) != -1 && !((num >= '0' && num <= '9') || num == '-'));
			if(num == '-'){
				num = 0;
				minus = true;
			}else{
				num -= '0';
			}

			while(true){
				int b = is.read();
				if(b >= '0' && b <= '9'){
					num = num * 10 + (b - '0');
				}else{
					return minus ? -num : num;
				}
			}
		} catch (IOException e) {
		}
		return -1;
	}

	public long nl()
	{
		try {
			long num = 0;
			boolean minus = false;
			while((num = is.read()) != -1 && !((num >= '0' && num <= '9') || num == '-'));
			if(num == '-'){
				num = 0;
				minus = true;
			}else{
				num -= '0';
			}

			while(true){
				int b = is.read();
				if(b >= '0' && b <= '9'){
					num = num * 10 + (b - '0');
				}else{
					return minus ? -num : num;
				}
			}
		} catch (IOException e) {
		}
		return -1;
	}

	public String ns()
	{
		try{
			int b = 0;
			StringBuilder sb = new StringBuilder();
			while((b = is.read()) != -1 && (b == '\r' || b == '\n' || b == ' '));
			if(b == -1)return "";
			sb.append((char)b);
			while(true){
				b = is.read();
				if(b == -1)return sb.toString();
				if(b == '\r' || b == '\n' || b == ' ')return sb.toString();
				sb.append((char)b);
			}
		} catch (IOException e) {
		}
		return "";
	}

	public char[] ns(int n)
	{
		char[] buf = new char[n];
		try{
			int b = 0, p = 0;
			while((b = is.read()) != -1 && (b == ' ' || b == '\r' || b == '\n'));
			if(b == -1)return null;
			buf[p++] = (char)b;
			while(p < n){
				b = is.read();
				if(b == -1 || b == ' ' || b == '\r' || b == '\n')break;
				buf[p++] = (char)b;
			}
			return Arrays.copyOf(buf, p);
		} catch (IOException e) {
		}
		return null;
	}

	double nd() { return Double.parseDouble(ns()); }
	boolean oj = System.getProperty("ONLINE_JUDGE") != null;
	void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}


import java.util.*;
public class asd
{
         public static void main(String args[])throws Exception
         {
                  Scanner s=new Scanner(System.in);
                  int n=s.nextInt();
                  String str=s.next();int count=0;
                  for(int i=2;i<str.length();i++)
                  {
                           char ch1=str.charAt(i-2);
                           char ch2=str.charAt(i-1);
                           char ch3=str.charAt(i);
                           if(ch1=='x'&&ch2=='x'&&ch3=='x')
                           counnt++;
                  }
                  System.out.println(count);
         }
}


import java.util.*;
public class sub {
      public static void main(String[] args) {
        // TODO code application logic here
        Scanner scan=new Scanner(System.in);
        int n,count=0;

        n=scan.nextInt();
        String s1;
         while(n>0)
        {
            c= scan.next().charAt(0);
            s1=s1+c;
            n--;
        }
        for(int i=0;i<s1.length()-2;i++)
        {
            if("xxx".equals(s1.substring(i,i+3)))
                count++;
        }
        System.out.println(count);
}
}


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

public class Main
{
	public BufferedReader in;
	public PrintStream out;

	public boolean log_enabled = false;

	static long[] primes;
	static int p_count;

	public static void get_primes(int n)
	{
		primes = new long[80000];

		boolean[] v = new boolean[n+1];
		int i,j;
		for (i=2; i<=n;i++)
		{
			v[i] = true;
		}

		for (i=2; i*i<=n;i++)
		{
			if (v[i])
			{
				for (j=i; i*j<=n; j++)
				{
					v[i*j]=false;
				}
			}
		}

		p_count = 0;
		for (i=2; i<=n; i++)
		{
			if (v[i])
			{
				primes[p_count++] = i;
			}
		}
	}

	int d_count;
	int[] d_index;
	long A;

	public int d_index(long x)
	{
		if ( (x<1000000) && (x*x<=A))
		{
			return d_index[(int)x];
		}
		else
		{
			return d_count - d_index[(int)(A/x)] - 1;
		}
	}

	public void test()
	{
		get_primes(1000000);

		A = readLong();
		long[] dividers = new long[10000];
		d_count = 0;

		d_index = new int[1000000];

		long[] use_primes = new long[10000];
		int use_p_count = 0;

		boolean[] p_used = new boolean[1000000];
		Arrays.fill(p_used, false);

		int i;
		for (i=1; i*i<=A; i++)
		{
			if (A % i == 0)
			{
				d_index[i] = d_count;
				dividers[d_count++] = i;
			}
		}

		for (i=0; i<d_count; i++)
		{
			dividers[2*d_count-i-1] = A / dividers[i];
		}

		d_count *= 2;

		long d;
		int p;
		boolean is_prime;

		for (i=1; i<d_count; i++)
		{
			is_prime = true;
			d = dividers[i]-1;

			if (d==1) continue;

			for ( p=0; p<p_count; p++)
			{
				if (primes[p]*primes[p] > d)
				{
					break;
				}

				if (d % primes[p] == 0)
				{
					is_prime = false;
					while (d % primes[p] == 0)
					{
						d /= primes[p];
					}
					if (d==1)
					{
						if (!p_used[(int)primes[p]])
						{
							use_primes[use_p_count++] = primes[p];
						}
					}
				}
			}

			if (is_prime)
			{
				if ((d > 1000000) || !p_used[(int)d])
				{
					use_primes[use_p_count++] = d;
				}
			}
		}

		logWrite("use_p_count = %d\n", use_p_count);

		long[] D = new long[d_count];
		Arrays.fill(D, 0);
		D[0] = 1;

		for (p=0; p<use_p_count; p++)
		{
			for (i=1; i<d_count; i++)
			{
				logWrite("P = %d\n", use_primes[p]);

				d = use_primes[p];
				while (d<dividers[i])
				{
					if (dividers[i] % (d+1) == 0)
					{
						D[i] += D[d_index(dividers[i] / (d+1))];
					}

					d *= use_primes[p];
				}
			}
		}

		out.println(D[d_count-1]);
	}

	public void run()
	{
		try
		{
			in = new BufferedReader(new InputStreamReader(System.in));
			out = System.out;

			//in = new BufferedReader(new FileReader("in.txt"));
			//out = new PrintStream(new File("out.txt"));

		}
		catch (Exception e)
		{
			return;
		}

		//while (true)
		{
			//int t = readInt(); for (int i=0; i<t; i++)
			{
				test();
			}
		}
	}

	public static void main(String args[])
	{
		new Main().run();
	}

	private StringTokenizer tokenizer = null;

	public int readInt()
	{
        return Integer.parseInt(readToken());
    }

    public long readLong()
	{
        return Long.parseLong(readToken());
    }

    public double readDouble()
	{
        return Double.parseDouble(readToken());
    }

	public String readLn()
	{
		try
		{
			String s;
			while ((s = in.readLine()).length()==0);
			return s;
		}
		catch (Exception e)
		{
			return "";
		}
	}

    public String readToken()
	{
		try
		{
			while (tokenizer == null || !tokenizer.hasMoreTokens())
			{
				tokenizer = new StringTokenizer(in.readLine());
			}
			return tokenizer.nextToken();
		}
		catch (Exception e)
		{
			return "";
		}
    }

	public int[] readIntArray(int n)
	{
		int[] x = new int[n];
		readIntArray(x, n);
		return x;
	}

	public void readIntArray(int[] x, int n)
	{
		for (int i=0; i<n; i++)
		{
			x[i] = readInt();
		}
	}

	public void logWrite(String format, Object... args)
	{
		if (!log_enabled)
		{
			return;
		}

		out.printf(format, args);
	}
}