import java.util.*;
import java.io.*;
public class E{
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

        int n, m;
        String reader = br.readLine();
        n = Integer.parseInt(reader.split(" ")[0]);
        m = Integer.parseInt(reader.split(" ")[1]);

        reader = br.readLine();
        int[] a = new int[n];
        for (int i = 0; i < n; i++) {
            a[i] = Integer.parseInt(reader.split(" ")[i]);
        }

        int half_n = (n + 1) / 2;
        Set<Integer> set = new HashSet<>();
        set.add(0);
        for (int i = 0; i < half_n; i++) {
            Set<Integer> newSet = new HashSet<>();
            for (int num: set) {
                newSet.add((num + a[i]) % m);
            }
            set.addAll(newSet);
        }

        Integer[] first_sorted = set.toArray(new Integer[0]);
        Arrays.sort(first_sorted);

        Set<Integer> second_set = new HashSet<>();
        second_set.add(0);
        for (int i = half_n; i < n; i++) {
            Set<Integer> newSet = new HashSet<>();
            for (int num: second_set) {
                newSet.add((num + a[i]) % m);
            }
            second_set.addAll(newSet);
        }

        int max = 0;
        for (int num: second_set) {
            max = Math.max(max, num);
            int idx = Arrays.binarySearch(first_sorted, m - num - 1);
            if (idx < 0) {
                idx = - (idx + 1) - 1;
            }
            max = Math.max(max, num + first_sorted[idx]);
        }
        max = Math.max(max, first_sorted[first_sorted.length - 1]);

        StringBuffer sb = new StringBuffer();
        sb.append(max);
        bw.write(sb.toString());
        bw.flush();
    }
}

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

public class E888 {

	int n;
	long m;
	int l;
	int r;

	private void solve() throws Exception {
		n = nextInt();
		m = nextInt();
		l = n/2;
		r = n-l;
		long[] al = new long[l];
		for(int i = 0; i < l; i++) al[i] = nextLong()%m;
		long[] ar = new long[r];
		for(int i = 0; i < r; i++) ar[i] = nextLong()%m;
		long[] part1 = doit(al);
		long[] part2 = doit(ar);
		long best = 0;
		for(int i = 0; i < part1.length; i++){
			int left = 0;
			int right = part2.length;
			while(left < right-1) {
				int mid = (left+right)/2;
				if(part1[i] + part2[mid] < m) left = mid;
				else right = mid;
			}
			best = Math.max(best, (part1[i]+part2[left])%m);
			left = Math.min(part2.length-1, right+1);
			right = part2.length;
			while(left < right-1) {
				int mid = (left+right)/2;
				if(part1[i] + part2[mid] < 2*m) left = mid;
				else right = mid;
			}
			best = Math.max(best, (part1[i]+part2[left])%m);
		}
		out.println(best);
	}

	long[] doit(long[] a) {
		int n = a.length;
		long[] res = new long[(1<<n)];
		for(int i = 0; i < (1<<n); i++) {
			int ii = i;
			for(int j = 0; j < n; j++, ii >>= 1) if(ii%2 == 1) res[i] = (res[i]+a[j])%m;
		}
		Arrays.sort(res);
		return res;
	}

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

	private BufferedReader in;
	private PrintWriter out;
	private StringTokenizer tokenizer;

	public void run() {
		try {
			in = new BufferedReader(new InputStreamReader(System.in));
			tokenizer = null;
			out = new PrintWriter(System.out);
			solve();
			in.close();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(1);
		}
	}

	private int nextInt() throws IOException {
		return Integer.parseInt(nextToken());
	}

	private long nextLong() throws IOException {
		return Long.parseLong(nextToken());
	}

	private float nextFloat() throws IOException {
		return Float.parseFloat(nextToken());
	}

	private String nextLine() throws IOException {
		return new String(in.readLine());
	}

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

}

import java.lang.reflect.Array;
import java.util.*;

public class Main {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        int n = scanner.nextInt();
        int m = scanner.nextInt();
        int[] a= new int[n];
        for (int i = 0; i < n; i++) {
            a[i] =scanner.nextInt();
            a[i] = a[i] % m;
        }
        int n1 = n / 2;

        int[] a1 = new int[n1 + 1];
        for (int i = 0; i <= n1; i++) {
            a1[i] = 0;
        }

        Set<Integer> b1 = new HashSet<Integer>();
        while (a1[n1] == 0) {
            a1[0]++;
            for (int i = 0; a1[i] == 2; i++) {
                a1[i] = 0;
                a1[i + 1]++;
            }
            int temp = 0;
            for (int i = 0; i < n1; i++) {
                if (a1[i] == 1) {
                    temp = (temp + a[i]) % m;
                }
            }
            b1.add(temp);

        }

        int n2 = n - n1;
        int[] a2 = new int[n2 + 1];
        for (int i = 0; i <= n2; i++) {
            a2[i] = 0;
        }

        Set<Integer> b2 = new HashSet<Integer>();
        while (a2[n2] == 0) {
            a2[0]++;
            for (int i = 0; a2[i] == 2; i++) {
                a2[i] = 0;
                a2[i + 1]++;
            }
            int temp = 0;
            for (int i = 0; i < n2; i++)
                if (a2[i] == 1) {
                    temp = (temp + a[i + n1]) % m;
                }
            b2.add(temp);
        }

        int max = 0;
        for (int i : b1)
            if (i > max) {
                max = i;
            }
        for (int i : b2)
            if (i > max) {
                max = i;
            }
        int b1Size = b1.size();
        int[] c1 = new int[b1Size];
        int count = -1;
        for (int i : b1) {
            count++;
            c1[count] = i;
        }
        int b2Size = b2.size();
        int[] c2 = new int[b2Size];
        count = -1;
        for (int i : b2) {
            count++;
            c2[count] = i;
        }
        Arrays.sort(c2);
        for (int i = 0; i < b1Size; i++) {
            int index = find(c2, m - c1[i]);
            if (c1[i] + c2[index] > max) {
                max = c1[i] + c2[index];
            }
        }
        System.out.print(max);
    }

    public static int find(int[] array, int des) {
        int left = 0;
        int right = Array.getLength(array) - 1;
        int res = -1;
        while (left <= right) {
            int mid = (left + right) / 2;
            if (array[mid] < des) {
                res = mid;
                left = mid + 1;
            } else {
                right = mid -1;
            }
        }
        return res;
    }

}

import java.util.*;
import java.io.*;
import java.lang.*;
public class E32E {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner sc =new Scanner(System.in);
		int n =sc.nextInt();
		int m =sc.nextInt();
		int f=n/2,l=n-f;
		long a[] =new long[f];
		long b[] =new long[l];
		for(int i=0;i<f;i++){
			a[i]=sc.nextInt();
		}
		for(int i=0;i<l;i++){
			b[i]=sc.nextInt();
		}
		int sf[] =new int[1<<f];
		int sl[] =new int[1<<l];
		for(int i=1;i<(1<<f);i++){
			for(int j=0;j<f;j++){
				if((i&(1<<j))>0){
					sf[i]=(int)(sf[i]+a[j])%m;
				}
			}
		}
		Arrays.sort(sf);
		for(int i=1;i<(1<<l);i++){
			for(int j=0;j<l;j++){
				if((i&(1<<j))>0){
					sl[i]=(int)(sl[i]+b[j])%m;
				}
			}
		}
		Arrays.sort(sl);
		int max =Integer.MIN_VALUE;
		for(int i=0;i<sf.length;i++){
			int find =(int)(m-1-sf[i]);
			int in=Arrays.binarySearch(sl,find);
			if(in<-1){
				in =-in-2;
				int temp=sl[in]+sf[i];
				if(temp>max){
					max=temp;
				}
			}
			else if(in>=0){
				//System.out.println(in);
				max=m-1;
				break;
			}
		}
		if(max!=m-1){
		for(int i=0;i<sl.length;i++){
			int find =(int)(m-1-sl[i]);
			int in=Arrays.binarySearch(sf,find);
			if(in<-1){
				in =-in-2;
				int temp=sf[in]+sl[i];
				if(temp>max){
					max=temp;
				}
			}
			else if(in>=0){
				max=m-1;
				break;
			}
		}
		}
		System.out.println(max);
	}

}

/*
 * DA-IICT
 * Author: Jugal Kalal
 */
import java.util.*;
import java.io.*;
import java.math.*;
import java.text.DecimalFormat;
public class Hackerrank{
	static long mod=(long)Math.pow(10,9)+7;
	public static void main(String args[]) {
        new Thread(null, new Runnable() {
            public void run() {
                try{
                    solve();
                    w.close();
                }
                catch(Exception e){
                    e.printStackTrace();
                }
            }
        }, "1", 1 << 26).start();
	}
	static InputReader in;
    static PrintWriter w;
    static void solve(){
        in = new InputReader(System.in);
        w = new PrintWriter(System.out);
        int n=in.nextInt();
        long m=in.nextLong();
        long arr[]=in.nextLongArray(n);
        int fp=n/2;
        TreeSet<Long> set1=new TreeSet<>();
        TreeSet<Long> set2=new TreeSet<>();
        for(int i=0;i<Math.pow(2,fp);i++) {
        		long sum=0;
        		for(int j=0;j<fp;j++) {
        			if(((1<<j)&i)!=0) {
        				sum=(sum+arr[j])%m;
        			}
        		}
        		set1.add(sum);
        }
        for(int i=0;i<Math.pow(2, n-fp);i++) {
        		long sum=0;
        		for(int j=0;j<(n-fp);j++) {
        			if(((1<<j)&i)!=0) {
        				sum=(sum+arr[j+fp])%m;
        			}
        		}
        		set2.add(sum);
        }
        long max=0;
        for(long x:set1) {
        		Long val1=set2.lower(m-x);
        		if(val1==null) {
        			val1=0L;
        		}
        		Long val2=set2.lower(2*x-m);
        		if(val2==null) {
        			val2=0L;
        		}
        		max=Math.max(max,Math.max((val1+x)%m,(val2+x)%m));
        }
        w.println(max);
    }
	static class Pair{
			int parent;
			int type;
			public Pair(int parent,int type) {
				this.parent=parent;
				this.type=type;
			}
	}
	static class Triple{
			int f;
			int s;
			int t;
			public Triple(int f,int s,int t) {
				this.f=f;
				this.s=s;
				this.t=t;
			}
	}
    static int parent[];
    static TreeMap<Integer,ArrayList<Integer>> levels=new TreeMap<>(Collections.reverseOrder());
    static void bfs(int s,int n) {
    		boolean vis[]=new boolean[n];
    		Queue<Integer> queue=new LinkedList<>();
    		Queue<Integer> lev=new LinkedList<>();
    		queue.add(s);
    		vis[s]=true;
    		lev.add(0);
    		parent[0]=-1;
    		while(!queue.isEmpty()) {
    			int top=queue.poll();
    			int l=lev.poll();
    			ArrayList<Integer> temp;
    			if(levels.containsKey(l)) {
    				temp=levels.get(l);
    			}else {
    				temp=new ArrayList<>();
    			}
    			temp.add(top);
    			levels.put(l,temp);
    			for(int v:adj[top]) {
    				if(!vis[v]) {
    					vis[v]=true;
    					lev.add(l+1);
    					queue.add(v);
    				}
    			}
    		}
    }
    static ArrayList<Integer> adj[]; //Adjacency Lists
    static int V;   // No. of vertices
    // Constructor
    static void Graph(int v){
        V = v;
        adj = new ArrayList[v];
        for (int i=0; i<v; ++i){
        		adj[i] = new ArrayList();
        }
    }

    // Function to add an edge into the graph
    static void addEdge(int u,int v){
		adj[u].add(v);
		adj[v].add(u);
    }
//    static long[] isHamiltonian_path(int n){
//    	boolean dp[][]=new boolean[n][1<<n];
//    	long ans[]=new long[n];
//    	long sum[]=new long[n];
//    	for(int i=0;i<n;i++){
//    		dp[i][1<<i]=true;
//    		ans[i]=0;
//    		sum[i]=i+1;
//    	}
//    	for(int mask=0;mask<(1<<n);mask++){
//    		int s=0;
//    		int count=0,temp=mask;
//    		while(temp>0){
//    			s+=1+Math.log(temp&(-temp))/Math.log(2);
//    			temp=temp&(temp-1);
//    			count++;
//    		}
//    		for(int j=0;j<n;j++){
//    			if((mask&(1<<j))>0){
//    				for(int k=0;k<n;k++){
//    					if(j!=k&&(mask&(1<<k))>0&&adj[j][k]&&dp[k][mask^(1<<j)]){
//    						dp[j][mask]=true;
//    						ans[j]=Math.max(ans[j],count-1);
//    						if(ans[j]==count-1){
//    							sum[j]=Math.max(sum[j], s);
//    						}
//    					}
//    				}
//    			}
//    		}
//    	}
//    	return sum;
//    }
//    static void bfs(int s,int n){
//    	boolean visited[]=new boolean[n];
//    	LinkedList<Integer> queue=new LinkedList<Integer>();
//    	queue.add(s);
//    	visited[s]=true;
//    	while(!queue.isEmpty()){
//    		int num=queue.pop();
////    		System.out.println(ans.toString());
//    		for(int i=0;i<adj[num].size();i++){
//    			if(!visited[adj[num].get(i)]){
//    				visited[adj[num].get(i)]=true;
//    				queue.add(adj[num].get(i));
//    			}
//    		}
//    	}
//    }
    static long gcd(long a,long b){
		if(a==0){
			return b;
		}
		return gcd(b%a,a);
	}
    static long power(long base, long exponent, long modulus){
	    long result = 1L;
	    while (exponent > 0) {
	        if (exponent % 2L == 1L)
	            result = (result * base) % modulus;
	        exponent = exponent >> 1;
	        base = (base * base) % modulus;
	    }
	    return result;
	}
    static HashMap<Long,Long> primeFactors(long n){
        HashMap<Long,Long> ans=new HashMap<Long,Long>();
    	// Print the number of 2s that divide n
        while (n%2L==0L)
        {
            if(ans.containsKey(2L)){
            	ans.put(2L,ans.get(2L)+1L);
            }else{
            	ans.put(2L,1L);
            }
            n /= 2L;
        }

        // n must be odd at this point.  So we can
        // skip one element (Note i = i +2)
        for (long i = 3; i <= Math.sqrt(n); i+= 2L)
        {
            // While i divides n, print i and divide n
            while (n%i == 0)
            {
            	if(ans.containsKey(i)){
                	ans.put(i,ans.get(i)+1L);
                }else{
                	ans.put(i,1L);
                }
                n /= i;
            }
        }

        // This condition is to handle the case whien
        // n is a prime number greater than 2
        if (n > 2)
            ans.put(n,1L);
        return ans;
    }
////for marking all prime numbers greater than 1 and less than equal to N
	static boolean[] sieve(int N) {
		 boolean isPrime[]=new boolean[N+1];
		 isPrime[0] = true;
		 isPrime[1] = true;
		 for(int i = 2; i * i <= N; ++i) {
		      if(isPrime[i] == false) {//Mark all the multiples of i as composite numbers
		          for(int j = i * i; j <= N ;j += i)
		              isPrime[j] = true;
		     }
		 }
		 return isPrime;
	}
//  //if  str2 (pattern) is subsequence of str1 (Text) or not
//	static boolean function(String str1,String str2){
//	     str2 = str2.replace("", ".*");  //returns .*a.*n.*n.*a.
//	     return (str1.matches(str2));  // returns true
//	}
    static int Arr[];
    static long size[];
  //modified initialize function:
    static void initialize(int N){
    	Arr=new int[N];
    	size=new long[N];
        for(int i = 0;i<N;i++){
        	Arr[ i ] = i ;
        	size[ i ] = 1;
        }
    }
    static boolean find(int A,int B){
        if( root(A)==root(B) )       //if A and B have same root,means they are connected.
        return true;
        else
        return false;
    }
 // modified root function.
    static void weighted_union(int A,int B,int n){
        int root_A = root(A);
        int root_B = root(B);
        if(size[root_A] < size[root_B ]){
        	Arr[ root_A ] = Arr[root_B];
        	size[root_B] += size[root_A];
        }
        else{
        	Arr[ root_B ] = Arr[root_A];
        	size[root_A] += size[root_B];
        }
    }
    static int root (int i){
        while(Arr[ i ] != i){
            Arr[ i ] = Arr[ Arr[ i ] ] ;
            i = Arr[ i ];
        }
        return i;
    }

	static boolean isPrime(long n) {
		if(n < 2L) return false;
		if(n == 2L || n == 3L) return true;
		if(n%2L == 0 || n%3L == 0) return false;
		long sqrtN = (long)Math.sqrt(n)+1L;
		for(long i = 6L; i <= sqrtN; i += 6L) {
			if(n%(i-1) == 0 || n%(i+1) == 0) return false;
		}
		return true;
	}
//	static HashMap<Integer,Integer> level;;
//	static HashMap<Integer,Integer> parent;
	static int maxlevel=0;

//	static boolean T[][][];
//	static void subsetSum(int input[], int total, int count) {
//        T = new boolean[input.length + 1][total + 1][count+1];
//        for (int i = 0; i <= input.length; i++) {
//        	T[i][0][0] = true;
//        	for(int j = 1; j<=count; j++){
//        		T[i][0][j] = false;
//        	}
//        }
//        int sum[]=new int[input.length+1];
//        for(int i=1;i<=input.length;i++){
//            sum[i]=sum[i-1]+input[i-1];
//        }
//        for (int i = 1; i <= input.length; i++) {
//            for (int j = 1; j <= (int)Math.min(total,sum[i]); j++) {
//            	for (int k = 1; k <= (int)Math.min(i,count); k++){
//            		 if (j >= input[i - 1]) {//Exclude and Include
//                         T[i][j][k] = T[i - 1][j][k] || T[i - 1][j - input[i - 1]][k-1];
//                     } else {
//                         T[i][j][k] = T[i-1][j][k];
//                     }
//            	}
//            }
//        }
//    }
//	static <K,V extends Comparable<? super V>>
//	SortedSet<Map.Entry<K,V>> entriesSortedByValues(Map<K,V> map) {
//	    SortedSet<Map.Entry<K,V>> sortedEntries = new TreeSet<Map.Entry<K,V>>(
//	        new Comparator<Map.Entry<K,V>>() {
//	            @Override public int compare(Map.Entry<K,V> e1, Map.Entry<K,V> e2) {
//	                int res = e2.getValue().compareTo(e1.getValue());
//	                return res != 0 ? res : 1;
//	            }
//	        }
//	    );
//	    sortedEntries.addAll(map.entrySet());
//	    return sortedEntries;
//	}

	//minimum prime factor of all the numbers less than n
    static int minPrime[];
	static void minimumPrime(int n){
		minPrime=new int[n+1];
		minPrime[1]=1;
        for (int i = 2; i * i <= n; ++i) {
            if (minPrime[i] == 0) {         //If i is prime
                for (int j = i * i; j <= n; j += i) {
                    if (minPrime[j] == 0) {
                        minPrime[j] = i;
                    }
                }
            }
        }
        for (int i = 2; i <= n; ++i) {
            if (minPrime[i] == 0) {
                minPrime[i] = i;
            }
        }
	}
	static long modInverse(long A, long M)
	{
		long x=extendedEuclid(A,M)[0];
		return (x%M+M)%M;    //x may be negative
	}
	static long[] extendedEuclid(long A, long B) {
		if(B == 0) {
			long d = A;
			long x = 1;
			long y = 0;
			return new long[]{x,y,d};
		}
		else {
			long arr[]=extendedEuclid(B, A%B);
			long temp = arr[0];
			arr[0] = arr[1];
			arr[1] = temp - (A/B)*arr[1];
			return arr;
		}
	}

	static class InputReader {
        private final InputStream stream;
        private final byte[] buf = new byte[8192];
        private int curChar, numChars;
        private SpaceCharFilter filter;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars == -1) {
                throw new InputMismatchException();
            }
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (numChars <= 0) {
                    return -1;
                }
            }
            return buf[curChar++];
        }

        public String nextLine() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            StringBuilder res = new StringBuilder();
            do {
                res.appendCodePoint(c);
                c = read();
            } while (!isEndOfLine(c));
            return res.toString();
        }

        public String readString() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            StringBuilder res = new StringBuilder();
            do {
                res.appendCodePoint(c);
                c = read();
            } while (!isSpaceChar(c));
            return res.toString();
        }

        public long nextLong() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            long res = 0;
            do {
                if (c < '0' || c > '9') {
                    throw new InputMismatchException();
                }
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public int nextInt() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9') {
                    throw new InputMismatchException();
                }
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public int[] nextIntArray(int n) {
            int[] arr = new int[n];
            for (int i = 0; i < n; i++) {
                arr[i] = nextInt();
            }
            return arr;
        }

        public long[] nextLongArray(int n) {
            long[] arr = new long[n];
            for (int i = 0; i < n; i++) {
                arr[i] = nextLong();
            }
            return arr;
        }

        public boolean isSpaceChar(int c) {
            if (filter != null)
                return filter.isSpaceChar(c);
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        private boolean isEndOfLine(int c) {
            return c == '\n' || c == '\r' || c == -1;
        }
        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);
        }
	}
}

import java.io.*;
import java.util.*;
import java.util.Map.Entry;
import java.lang.Math;
import java.math.BigInteger;

public class Problem {

	void solve() throws IOException {

		int n = rI();
		int m = rI();
		int[] a;

		if(n%2==1){
			n++;
			a = new int[n];
			a[n-1] = 0;
			for(int i=0;i<n-1;++i){
				a[i] = rI();
			}
		}else{
			a = rA(n);
		}

		long bp = binPow(2, n/2);
		TreeSet<Integer> st1 = new TreeSet<>();
		TreeSet<Integer> st2 = new TreeSet<>();
		for (int mask = 0; mask < bp; ++mask) {
			int sum = 0;
			for (int bit = 0; bit < n/2; ++bit) {
				if (checkBit(mask, bit) == 1) {
					sum = (sum + a[bit] % m) % m;
				}
			}
			st1.add(sum);
		}

		for (int mask = 0; mask < bp; ++mask) {
			int sum = 0;
			for (int bit = 0; bit < n/2 ; ++bit) {
				if (checkBit(mask, bit) == 1) {
					sum = (sum + a[n/2+bit] % m) % m;
				}
			}
			st2.add(sum);
		}

		int ans = 0;

		for(int i: st1){
			int j = 0;
			if(st2.lower(m-i)!=null){
				j = st2.lower(m-i);
			}
			ans = Math.max(ans, i+j);
		}

		out.println(ans);
	}

	class SegmentTree {
		int[] t;

		SegmentTree(int[] a, int n) {
			t = new int[4 * n];
			build(a, 1, 1, n);
		}

		void build(int[] a, int v, int tl, int tr) {
			if (tl == tr) {
				t[v] = a[tl];
				return;
			}

			int tm = (tl + tr) / 2;
			build(a, 2 * v, tl, tm);
			build(a, 2 * v + 1, tm + 1, tr);
			t[v] = Math.min(t[2 * v], t[2 * v + 1]);
		}

		void update(int v, int tl, int tr, int pos, int value) {
			if (tl == tr) {
				t[v] = value;
				return;
			}
			int tm = (tl + tr) / 2;
			if (pos <= tm) {
				update(2 * v, tl, tm, pos, value);
			} else {
				update(2 * v + 1, tm + 1, tr, pos, value);
			}

			t[v] = Math.min(t[2 * v], t[2 * v + 1]);
		}

		int getMin(int v, int tl, int tr, int l, int r) {
			if (l > r) {
				return INF;
			}
			if (tl == l && tr == r) {
				return t[v];
			}

			int tm = (tl + tr) / 2;

			int min1 = getMin(2 * v, tl, tm, l, Math.min(tm, r));
			int min2 = getMin(2 * v + 1, tm + 1, tr, Math.max(l, tm + 1), r);

			return Math.min(min1, min2);
		}
	}

	int checkBit(int mask, int bit) {
		return (mask >> bit) & 1;
	}

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

		new Problem().run();
	}

	boolean isLower(char a) {
		return ((int) a) >= 97 ? true : false;
	}

	int INF = Integer.MAX_VALUE - 12345;

	int[][] STEPS = { { 0, 1 }, { 1, 0 }, { -1, 0 }, { 0, -1 } };

	BufferedReader in;
	PrintWriter out;
	StringTokenizer tok;
	Random rnd = new Random();
	static final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;

	Problem() throws FileNotFoundException {

		try {
			in = new BufferedReader(new FileReader("input.txt"));
			out = new PrintWriter("output.txt");
		} catch (Exception e) {
			in = new BufferedReader(new InputStreamReader(System.in));
			out = new PrintWriter(System.out);
		}

		tok = new StringTokenizer("");
	}

	long checkBit(long mask, int bit) {
		return (mask >> bit) & 1;
	}

	// ======================================================

	// ======================================================
	void run() throws IOException {
		solve();
		out.close();
	}

	char[] reverseCharArray(char[] arr) {
		char[] ans = new char[arr.length];
		for (int i = 0; i < arr.length; ++i) {
			ans[i] = arr[arr.length - i - 1];
		}
		return ans;
	}

	int sqrt(double m) {
		int l = 0;
		int r = 1000000000 + 9;
		int i = 1000;
		while (r - l > 1) {
			int mid = (r + l) / 2;
			if (mid * mid > m) {
				r = mid;
			} else {
				l = mid;
			}
		}
		return l;
	}

	int countPow(int m, int n) {
		int ans = 0;
		while (m % n == 0 && m > 0) {
			ans++;
			m /= n;
		}
		return ans;
	}

	long binPow(long a, long b) {
		if (b == 0) {
			return 1;
		}
		if (b % 2 == 1) {
			return a * binPow(a, b - 1);
		} else {
			long c = binPow(a, b / 2);
			return c * c;
		}

	}

	int gcd(int a, int b) {
		return b == 0 ? a : gcd(b, a % b);
	}

	long pow(long x, long k) {
		long ans = 1;
		for (int i = 0; i < k; ++i) {
			ans *= x;
		}
		return ans;
	}

	class Fenwik {
		private long[] t;
		private int length;

		Fenwik(int[] a) {
			this.length = a.length + 100;
			this.t = new long[length];
			for (int i = 0; i < a.length; ++i) {
				this.inc(i, a[i]);
			}
		}

		void inc(int i, int delta) {
			for (; i < this.length; i = i | (i + 1)) {
				this.t[i] += delta;
			}
		}

		long getSum(int r) {
			long sum = 0;

			for (; r >= 0; r = (r & (r + 1)) - 1) {
				sum += this.t[r];
			}

			return sum;
		}
	}

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

	String delimiter = " ";

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

	String rS() throws IOException {
		while (!tok.hasMoreTokens()) {
			String nextLine = readLine();
			if (null == nextLine)
				return null;

			tok = new StringTokenizer(nextLine);
		}

		return tok.nextToken(delimiter);
	}

	int rI() throws IOException {
		return Integer.parseInt(rS());
	}

	long rL() throws IOException {
		return Long.parseLong(rS());
	}

	double rD() throws IOException {
		return Double.parseDouble(rS());
	}

	int[] rA(int b) {
		int a[] = new int[b];
		for (int i = 0; i < b; i++) {
			try {
				a[i] = rI();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return a;
	}

	int[] readSortedIntArray(int size) throws IOException {
		Integer[] array = new Integer[size];

		for (int index = 0; index < size; ++index) {
			array[index] = rI();
		}
		Arrays.sort(array);

		int[] sortedArray = new int[size];
		for (int index = 0; index < size; ++index) {
			sortedArray[index] = array[index];
		}

		return sortedArray;
	}

	int[] sortedIntArray(int size, int[] array) throws IOException {
		for (int index = 0; index < size; ++index) {
			array[index] = rI();
		}
		Arrays.sort(array);

		int[] sortedArray = new int[size];
		for (int index = 0; index < size; ++index) {
			sortedArray[index] = array[index];
		}

		return sortedArray;
	}
}

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

public class _888_E_MaximumSubsequence {

	public static void main(String[] args) throws IOException {
		int N = readInt(), M = readInt(), mid = N/2; int a1[] = new int[mid], a2[] = new int[N-mid];
		for(int i = 0; i<mid; i++) a1[i] = readInt(); for(int i = mid; i<N; i++) a2[i-mid] = readInt();
		Integer arr1[] = new Integer[1<<mid], arr2[] = new Integer[1<<(N-mid)]; Arrays.fill(arr1, 0); Arrays.fill(arr2, 0);
		for(int i = 0; i<(1<<mid); i++) for(int j = 0; j<mid; j++) if(((1<<j)&i) != 0) arr1[i] = (arr1[i] + a1[j])%M;
		for(int i = 0; i<(1<<(N-mid)); i++) for(int j = 0; j<N-mid; j++) if(((1<<j)&i) != 0) arr2[i] = (arr2[i] + a2[j])%M;
		Arrays.sort(arr1); Arrays.sort(arr2); int max = 0;
		for(int i = 0, j = (1<<(N-mid))-1; i<(1<<mid); i++) {
			while(arr1[i] + arr2[j] >= M) j--; max = (int) Math.max(max, arr1[i] + arr2[j]);
		}
		println(max);
		exit();
	}

	final private static int BUFFER_SIZE = 1 << 16;
	private static DataInputStream din = new DataInputStream(System.in);
	private static byte[] buffer = new byte[BUFFER_SIZE];
	private static int bufferPointer = 0, bytesRead = 0;
	static PrintWriter pr = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));

	public static String readLine() throws IOException {
		byte[] buf = new byte[64]; // line length
		int cnt = 0, c;
		while ((c = Read()) != -1) {
			if (c == '\n')
				break;
			buf[cnt++] = (byte) c;
		}
		return new String(buf, 0, cnt);
	}

	public static String read() throws IOException {
		byte[] ret = new byte[1024];
		int idx = 0;
		byte c = Read();
		while (c <= ' ') {
			c = Read();
		}
		do {
			ret[idx++] = c;
			c = Read();
		} while (c != -1 && c != ' ' && c != '\n' && c != '\r');
		return new String(ret, 0, idx);
	}

	public static int readInt() 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 static long readLong() 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 static double readDouble() 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 static void fillBuffer() throws IOException {
		bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
		if (bytesRead == -1)
			buffer[0] = -1;
	}

	private static byte Read() throws IOException {
		if (bufferPointer == bytesRead)
			fillBuffer();
		return buffer[bufferPointer++];
	}

	public void close() throws IOException {
		if (din == null)
			return;
		din.close();
	}

	static void print(Object o) {
		pr.print(o);
	}

	static void println(Object o) {
		pr.println(o);
	}

	static void flush() {
		pr.flush();
	}

	static void println() {
		pr.println();
	}

	static void exit() throws IOException {
		din.close();
		pr.close();
		System.exit(0);
	}
}

import java.io.*;
import java.util.*;
import java.util.Map.Entry;
import java.lang.Math;
import java.math.BigInteger;

public class Problem {

	void solve() throws IOException {

		int n = rI();
		int m = rI();
		int[] a;

		if(n%2==1){
			n++;
			a = new int[n];
			a[n-1] = 0;
			for(int i=0;i<n-1;++i){
				a[i] = rI();
			}
		}else{
			a = rA(n);
		}

		long bp = binPow(2, n/2);
		TreeSet<Integer> st1 = new TreeSet<>();
		TreeSet<Integer> st2 = new TreeSet<>();
		for (int mask = 0; mask < bp; ++mask) {
			int sum = 0;
			for (int bit = 0; bit < n/2; ++bit) {
				if (checkBit(mask, bit) == 1) {
					sum = (sum + a[bit] % m) % m;
				}
			}
			st1.add(sum);
		}

		for (int mask = 0; mask < bp; ++mask) {
			int sum = 0;
			for (int bit = 0; bit < n/2 ; ++bit) {
				if (checkBit(mask, bit) == 1) {
					sum = (sum + a[n/2+bit] % m) % m;
				}
			}
			st2.add(sum);
		}

		int ans = 0;

		for(int i: st1){
			int j = 0;
			if(st2.lower(m-i)!=null){
				j = st2.lower(m-i);
			}
			ans = Math.max(ans, i+j);
		}

		for(int i: st2){
			int j = 0;
			if(st1.lower(m-i)!=null){
				j = st1.lower(m-i);
			}
			ans = Math.max(ans, i+j);
		}
		out.println(ans);
	}

	class SegmentTree {
		int[] t;

		SegmentTree(int[] a, int n) {
			t = new int[4 * n];
			build(a, 1, 1, n);
		}

		void build(int[] a, int v, int tl, int tr) {
			if (tl == tr) {
				t[v] = a[tl];
				return;
			}

			int tm = (tl + tr) / 2;
			build(a, 2 * v, tl, tm);
			build(a, 2 * v + 1, tm + 1, tr);
			t[v] = Math.min(t[2 * v], t[2 * v + 1]);
		}

		void update(int v, int tl, int tr, int pos, int value) {
			if (tl == tr) {
				t[v] = value;
				return;
			}
			int tm = (tl + tr) / 2;
			if (pos <= tm) {
				update(2 * v, tl, tm, pos, value);
			} else {
				update(2 * v + 1, tm + 1, tr, pos, value);
			}

			t[v] = Math.min(t[2 * v], t[2 * v + 1]);
		}

		int getMin(int v, int tl, int tr, int l, int r) {
			if (l > r) {
				return INF;
			}
			if (tl == l && tr == r) {
				return t[v];
			}

			int tm = (tl + tr) / 2;

			int min1 = getMin(2 * v, tl, tm, l, Math.min(tm, r));
			int min2 = getMin(2 * v + 1, tm + 1, tr, Math.max(l, tm + 1), r);

			return Math.min(min1, min2);
		}
	}

	int checkBit(int mask, int bit) {
		return (mask >> bit) & 1;
	}

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

		new Problem().run();
	}

	boolean isLower(char a) {
		return ((int) a) >= 97 ? true : false;
	}

	int INF = Integer.MAX_VALUE - 12345;

	int[][] STEPS = { { 0, 1 }, { 1, 0 }, { -1, 0 }, { 0, -1 } };

	BufferedReader in;
	PrintWriter out;
	StringTokenizer tok;
	Random rnd = new Random();
	static final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;

	Problem() throws FileNotFoundException {

		try {
			in = new BufferedReader(new FileReader("input.txt"));
			out = new PrintWriter("output.txt");
		} catch (Exception e) {
			in = new BufferedReader(new InputStreamReader(System.in));
			out = new PrintWriter(System.out);
		}

		tok = new StringTokenizer("");
	}

	long checkBit(long mask, int bit) {
		return (mask >> bit) & 1;
	}

	// ======================================================

	// ======================================================
	void run() throws IOException {
		solve();
		out.close();
	}

	char[] reverseCharArray(char[] arr) {
		char[] ans = new char[arr.length];
		for (int i = 0; i < arr.length; ++i) {
			ans[i] = arr[arr.length - i - 1];
		}
		return ans;
	}

	int sqrt(double m) {
		int l = 0;
		int r = 1000000000 + 9;
		int i = 1000;
		while (r - l > 1) {
			int mid = (r + l) / 2;
			if (mid * mid > m) {
				r = mid;
			} else {
				l = mid;
			}
		}
		return l;
	}

	int countPow(int m, int n) {
		int ans = 0;
		while (m % n == 0 && m > 0) {
			ans++;
			m /= n;
		}
		return ans;
	}

	long binPow(long a, long b) {
		if (b == 0) {
			return 1;
		}
		if (b % 2 == 1) {
			return a * binPow(a, b - 1);
		} else {
			long c = binPow(a, b / 2);
			return c * c;
		}

	}

	int gcd(int a, int b) {
		return b == 0 ? a : gcd(b, a % b);
	}

	long pow(long x, long k) {
		long ans = 1;
		for (int i = 0; i < k; ++i) {
			ans *= x;
		}
		return ans;
	}

	class Fenwik {
		private long[] t;
		private int length;

		Fenwik(int[] a) {
			this.length = a.length + 100;
			this.t = new long[length];
			for (int i = 0; i < a.length; ++i) {
				this.inc(i, a[i]);
			}
		}

		void inc(int i, int delta) {
			for (; i < this.length; i = i | (i + 1)) {
				this.t[i] += delta;
			}
		}

		long getSum(int r) {
			long sum = 0;

			for (; r >= 0; r = (r & (r + 1)) - 1) {
				sum += this.t[r];
			}

			return sum;
		}
	}

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

	String delimiter = " ";

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

	String rS() throws IOException {
		while (!tok.hasMoreTokens()) {
			String nextLine = readLine();
			if (null == nextLine)
				return null;

			tok = new StringTokenizer(nextLine);
		}

		return tok.nextToken(delimiter);
	}

	int rI() throws IOException {
		return Integer.parseInt(rS());
	}

	long rL() throws IOException {
		return Long.parseLong(rS());
	}

	double rD() throws IOException {
		return Double.parseDouble(rS());
	}

	int[] rA(int b) {
		int a[] = new int[b];
		for (int i = 0; i < b; i++) {
			try {
				a[i] = rI();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return a;
	}

	int[] readSortedIntArray(int size) throws IOException {
		Integer[] array = new Integer[size];

		for (int index = 0; index < size; ++index) {
			array[index] = rI();
		}
		Arrays.sort(array);

		int[] sortedArray = new int[size];
		for (int index = 0; index < size; ++index) {
			sortedArray[index] = array[index];
		}

		return sortedArray;
	}

	int[] sortedIntArray(int size, int[] array) throws IOException {
		for (int index = 0; index < size; ++index) {
			array[index] = rI();
		}
		Arrays.sort(array);

		int[] sortedArray = new int[size];
		for (int index = 0; index < size; ++index) {
			sortedArray[index] = array[index];
		}

		return sortedArray;
	}
}

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

public class Main {

    static int n, m, mid;
    static int[] a;
    static TreeSet<Integer> set1 = new TreeSet<>();
    static int res = 0;

    public static void main(String[] args) throws Exception {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter out = new PrintWriter(System.out);
        StringTokenizer st = new StringTokenizer(in.readLine());
        n = Integer.parseInt(st.nextToken());
        m = Integer.parseInt(st.nextToken());
        a = new int[n];
        st = new StringTokenizer(in.readLine());
        for (int i = 0; i < n; i++) {
            a[i] = Integer.parseInt(st.nextToken()) % m;
        }
        mid = n/2;
        set1.add(0);
        recur(0, 0);
        recur(mid+1, 0);
        out.println(res);
        out.close();
    }

    static void recur(int pos, int sum) {
        if (pos == n) {
            int query = m-sum;
            res = Math.max(res, set1.lower(query) + sum);
            return;
        }
        int s2 = a[pos] + sum;
        s2 %= m;
        if (pos == mid) {
            set1.add(sum);
            set1.add(s2);
            return;
        }
        recur(pos+1, s2);
        recur(pos+1, sum);
    }

}
/*

 */

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

public class Main {

	static InputReader in = new InputReader(System.in);
	static PrintWriter out = new PrintWriter(System.out);

	static int oo = (int)1e9;
//	static long oo = (long)1e15;
//	static int mod = 1_000_000_007;
	static int mod = 998244353;

	static int[] dx = {1, 0, -1, 0};
	static int[] dy = {0, -1, 0, 1};

	static int M = 5001;
	static double EPS = 1e-13;
	static int num = 1;

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

		int n = in.nextInt();
		int m = in.nextInt();
		int[] a = in.nextIntArray(n);
		TreeSet<Integer> set1 = new TreeSet<>();
		TreeSet<Integer> set2 = new TreeSet<>();
		makeSet(set1, a, m, 0, n / 2, 0);
		makeSet(set2, a, m, n / 2, n, 0);
		int ans = 0;
		for(int i : set1) {
			Integer j = set2.lower(m - i);
			int cur = (i + j) % m;
			ans = Math.max(ans, cur);
		}
		System.out.println(ans);

		out.close();
	}

	static void makeSet(TreeSet<Integer> set, int[] a, int m, int i, int to, int cur) {
		if(i >= to) {
			set.add(cur);
			return;
		}
		makeSet(set, a, m, i+1, to, cur);
		makeSet(set, a, m, i+1, to, (cur + a[i]) % m);
	}

	static int find(int[] g, int x) {
		return g[x] = g[x] == x ? x : find(g, g[x]);
	}

	static void union(int[] g, int[] size, int x, int y) {
		x = find(g, x); y = find(g, y);
		if(x == y)
			return;
		if(size[x] < size[y]) {
			g[x] = y;
			size[y] += size[x];
		}
		else {
			g[y] = x;
			size[x] += size[y];
		}
	}

	static class Segment {
		Segment left, right;
		int size, minIdx;
//		int time, lazy;

		public Segment(int[] a, int l, int r) {
			super();
			if(l == r) {
				this.minIdx = l;
				this.size = 1;
				return;
			}
			int mid = (l + r) / 2;
			left = new Segment(a, l, mid);
			right = new Segment(a, mid+1, r);
			if(a[left.minIdx] <= a[right.minIdx])
				this.minIdx = left.minIdx;
			else
				this.minIdx = right.minIdx;
			this.size = left.size + right.size;
		}

		boolean covered(int ll, int rr, int l, int r) {
			return ll <= l && rr >= r;
		}

		boolean noIntersection(int ll, int rr, int l, int r) {
			return ll > r || rr < l;
		}

//		void lazyPropagation() {
//			if(lazy != 0) {
//				if(left != null) {
//					left.setLazy(this.time, this.lazy);
//					right.setLazy(this.time, this.lazy);
//				}
//				else {
//					val = lazy;
//				}
//			}
//		}

//		void setLazy(int time, int lazy) {
//			if(this.time != 0 && this.time <= time)
//				return;
//			this.time = time;
//			this.lazy = lazy;
//		}

		int querySize(int ll, int rr, int l, int r) {
//			lazyPropagation();
			if(noIntersection(ll, rr, l, r))
				return 0;
			if(covered(ll, rr, l, r))
				return size;
			int mid = (l + r) / 2;
			int leftSize = left.querySize(ll, rr, l, mid);
			int rightSize = right.querySize(ll, rr, mid+1, r);
			return leftSize + rightSize;
		}

		int query(int k, int l, int r) {
			Segment trace = this;
			while(l < r) {
				int mid = (l + r) / 2;
				if(trace.left.size > k) {
					trace = trace.left;
					r = mid;
				}
				else {
					k -= trace.left.size;
					trace = trace.right;
					l = mid + 1;
				}
			}
			return l;
		}

		void update(int ll, int rr, int l, int r) {
//			lazyPropagation();
			if(noIntersection(ll, rr, l, r))
				return;
			if(covered(ll, rr, l, r)) {
//				setLazy(time, knight);
				this.minIdx = -1;
				this.size = 0;
				return;
			}
			int mid = (l + r) / 2;
			left.update(ll, rr, l, mid);
			right.update(ll, rr, mid+1, r);
			this.size = left.size + right.size;
		}
	}

	static long pow(long a, long n, long mod) {
		if(n == 0)
			return 1;
		if(n % 2 == 1)
			return a * pow(a, n-1, mod) % mod;
		long x = pow(a, n / 2, mod);
		return x * x % mod;
	}

	static int[] getPi(char[] a) {
		int m = a.length;
		int j = 0;
		int[] pi = new int[m];
		for(int i = 1; i < m; ++i) {
			while(j > 0 && a[i] != a[j])
				j = pi[j-1];
			if(a[i] == a[j]) {
				pi[i] = j + 1;
				j++;
			}
		}
		return pi;
	}

	static long lcm(long a, long b) {
		return a * b / gcd(a, b);
	}

	static BigInteger lcm2(long a, long b) {
		long g = gcd(a, b);
		BigInteger gg = BigInteger.valueOf(g);
		BigInteger aa = BigInteger.valueOf(a);
		BigInteger bb = BigInteger.valueOf(b);
		return aa.multiply(bb).divide(gg);
	}

	static boolean nextPermutation(int[] a) {
		for(int i = a.length - 2; i >= 0; --i) {
			if(a[i] < a[i+1]) {
				for(int j = a.length - 1; ; --j) {
					if(a[i] < a[j]) {
						int t = a[i];
						a[i] = a[j];
						a[j] = t;
						for(i++, j = a.length - 1; i < j; ++i, --j) {
							t = a[i];
							a[i] = a[j];
							a[j] = t;
						}
						return true;
					}
				}
			}
		}
		return false;
	}

	static void shuffle(Object[] a) {
		Random r = new Random();
		for(int i = a.length - 1; i > 0; --i) {
			int si = r.nextInt(i);
			Object t = a[si];
			a[si] = a[i];
			a[i] = t;
		}
	}

	static void shuffle(int[] a) {
		Random r = new Random();
		for(int i = a.length - 1; i > 0; --i) {
			int si = r.nextInt(i);
			int t = a[si];
			a[si] = a[i];
			a[i] = t;
		}
	}

	static void shuffle(long[] a) {
		Random r = new Random();
		for(int i = a.length - 1; i > 0; --i) {
			int si = r.nextInt(i);
			long t = a[si];
			a[si] = a[i];
			a[i] = t;
		}
	}

	static int lower_bound(int[] a, int n, int k) {
		int s = 0;
		int e = n;
		int m;
		while (e - s > 0) {
			m = (s + e) / 2;
			if (a[m] < k)
				s = m + 1;
			else
				e = m;
		}
		return e;
	}
	static int lower_bound(long[] a, int n, long k) {
		int s = 0;
		int e = n;
		int m;
		while (e - s > 0) {
			m = (s + e) / 2;
			if (a[m] < k)
				s = m + 1;
			else
				e = m;
		}
		return e;
	}

	static int gcd(int a, int b) {
		return b == 0 ? a : gcd(b, a % b);
	}
	static long gcd(long a, long b) {
		return b == 0 ? a : gcd(b, a % b);
	}
	static BigInteger gcd(BigInteger a, BigInteger b) {
		return b.compareTo(BigInteger.ZERO) == 0 ? a : gcd(b, a.mod(b));
	}

	static class Pair implements Comparable<Pair> {
		int first, second;

		public Pair(int first, int second) {
			super();
			this.first = first;
			this.second = second;
		}

		@Override
		public int compareTo(Pair o) {
			return this.first != o.first ? this.first - o.first : this.second - o.second;
		}

//		@Override
//		public int compareTo(Pair o) {
//			return this.first != o.first ? o.first - this.first : o.second - this.second;
//		}

		@Override
		public int hashCode() {
			final int prime = 31;
			int result = 1;
			result = prime * result + first;
			result = prime * result + second;
			return result;
		}

		@Override
		public boolean equals(Object obj) {
			if (this == obj)
				return true;
			if (obj == null)
				return false;
			if (getClass() != obj.getClass())
				return false;
			Pair other = (Pair) obj;
			if (first != other.first)
				return false;
			if (second != other.second)
				return false;
			return true;
		}
	}
}

class InputReader {

	private final InputStream stream;
	private final byte[] buf = new byte[8192];
	private int curChar, snumChars;

	public InputReader(InputStream st) {
		this.stream = st;
	}

	public int read() {
		if (snumChars == -1)
			throw new InputMismatchException();
		if (curChar >= snumChars) {
			curChar = 0;
			try {
				snumChars = stream.read(buf);
			} catch (IOException e) {
				throw new InputMismatchException();
			}
			if (snumChars <= 0)
				return -1;
		}
		return buf[curChar++];
	}

	public int nextInt() {
		int c = read();
		while (isSpaceChar(c)) {
			c = read();
		}
		int sgn = 1;
		if (c == '-') {
			sgn = -1;
			c = read();
		}
		int res = 0;
		do {
			res *= 10;
			res += c - '0';
			c = read();
		} while (!isSpaceChar(c));
		return res * sgn;
	}

	public long nextLong() {
		int c = read();
		while (isSpaceChar(c)) {
			c = read();
		}
		int sgn = 1;
		if (c == '-') {
			sgn = -1;
			c = read();
		}
		long res = 0;
		do {
			res *= 10;
			res += c - '0';
			c = read();
		} while (!isSpaceChar(c));
		return res * sgn;
	}

	public int[] nextIntArray(int n) {
		int a[] = new int[n];
		for (int i = 0; i < n; i++) {
			a[i] = nextInt();
		}
		return a;
	}

	public String readString() {
		int c = read();
		while (isSpaceChar(c)) {
			c = read();
		}
		StringBuilder res = new StringBuilder();
		do {
			res.appendCodePoint(c);
			c = read();
		} while (!isSpaceChar(c));
		return res.toString();
	}

	public String nextLine() {
		int c = read();
		while (isSpaceChar(c))
			c = read();
		StringBuilder res = new StringBuilder();
		do {
			res.appendCodePoint(c);
			c = read();
		} while (!isEndOfLine(c));
		return res.toString();
	}

	public boolean isSpaceChar(int c) {
		return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
	}

	private boolean isEndOfLine(int c) {
		return c == '\n' || c == '\r' || c == -1;
	}

}

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

public class Main {

	static InputReader in = new InputReader(System.in);
	static PrintWriter out = new PrintWriter(System.out);

	static int oo = (int)1e9;
//	static long oo = (long)1e15;
//	static int mod = 1_000_000_007;
	static int mod = 998244353;

	static int[] dx = {1, 0, -1, 0};
	static int[] dy = {0, -1, 0, 1};

	static int M = 5001;
	static double EPS = 1e-13;
	static int num = 1;

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

		int n = in.nextInt();
		int m = in.nextInt();
		int[] a = in.nextIntArray(n);
		TreeSet<Integer> set1 = new TreeSet<>();
		TreeSet<Integer> set2 = new TreeSet<>();
		makeSet(set1, a, m, 0, n / 2, 0);
		makeSet(set2, a, m, n / 2, n, 0);
		int ans = 0;
		for(int i : set1) {
			Integer j = set2.lower(m - i);
			if(j == null) {
				j = set2.last();
			}
			int cur = (i + j) % m;
			ans = Math.max(ans, cur);
		}
		System.out.println(ans);

		out.close();
	}

	static void makeSet(TreeSet<Integer> set, int[] a, int m, int i, int to, int cur) {
		if(i >= to) {
			set.add(cur);
			return;
		}
		makeSet(set, a, m, i+1, to, cur);
		makeSet(set, a, m, i+1, to, (cur + a[i]) % m);
	}

	static int find(int[] g, int x) {
		return g[x] = g[x] == x ? x : find(g, g[x]);
	}

	static void union(int[] g, int[] size, int x, int y) {
		x = find(g, x); y = find(g, y);
		if(x == y)
			return;
		if(size[x] < size[y]) {
			g[x] = y;
			size[y] += size[x];
		}
		else {
			g[y] = x;
			size[x] += size[y];
		}
	}

	static class Segment {
		Segment left, right;
		int size, minIdx;
//		int time, lazy;

		public Segment(int[] a, int l, int r) {
			super();
			if(l == r) {
				this.minIdx = l;
				this.size = 1;
				return;
			}
			int mid = (l + r) / 2;
			left = new Segment(a, l, mid);
			right = new Segment(a, mid+1, r);
			if(a[left.minIdx] <= a[right.minIdx])
				this.minIdx = left.minIdx;
			else
				this.minIdx = right.minIdx;
			this.size = left.size + right.size;
		}

		boolean covered(int ll, int rr, int l, int r) {
			return ll <= l && rr >= r;
		}

		boolean noIntersection(int ll, int rr, int l, int r) {
			return ll > r || rr < l;
		}

//		void lazyPropagation() {
//			if(lazy != 0) {
//				if(left != null) {
//					left.setLazy(this.time, this.lazy);
//					right.setLazy(this.time, this.lazy);
//				}
//				else {
//					val = lazy;
//				}
//			}
//		}

//		void setLazy(int time, int lazy) {
//			if(this.time != 0 && this.time <= time)
//				return;
//			this.time = time;
//			this.lazy = lazy;
//		}

		int querySize(int ll, int rr, int l, int r) {
//			lazyPropagation();
			if(noIntersection(ll, rr, l, r))
				return 0;
			if(covered(ll, rr, l, r))
				return size;
			int mid = (l + r) / 2;
			int leftSize = left.querySize(ll, rr, l, mid);
			int rightSize = right.querySize(ll, rr, mid+1, r);
			return leftSize + rightSize;
		}

		int query(int k, int l, int r) {
			Segment trace = this;
			while(l < r) {
				int mid = (l + r) / 2;
				if(trace.left.size > k) {
					trace = trace.left;
					r = mid;
				}
				else {
					k -= trace.left.size;
					trace = trace.right;
					l = mid + 1;
				}
			}
			return l;
		}

		void update(int ll, int rr, int l, int r) {
//			lazyPropagation();
			if(noIntersection(ll, rr, l, r))
				return;
			if(covered(ll, rr, l, r)) {
//				setLazy(time, knight);
				this.minIdx = -1;
				this.size = 0;
				return;
			}
			int mid = (l + r) / 2;
			left.update(ll, rr, l, mid);
			right.update(ll, rr, mid+1, r);
			this.size = left.size + right.size;
		}
	}

	static long pow(long a, long n, long mod) {
		if(n == 0)
			return 1;
		if(n % 2 == 1)
			return a * pow(a, n-1, mod) % mod;
		long x = pow(a, n / 2, mod);
		return x * x % mod;
	}

	static int[] getPi(char[] a) {
		int m = a.length;
		int j = 0;
		int[] pi = new int[m];
		for(int i = 1; i < m; ++i) {
			while(j > 0 && a[i] != a[j])
				j = pi[j-1];
			if(a[i] == a[j]) {
				pi[i] = j + 1;
				j++;
			}
		}
		return pi;
	}

	static long lcm(long a, long b) {
		return a * b / gcd(a, b);
	}

	static BigInteger lcm2(long a, long b) {
		long g = gcd(a, b);
		BigInteger gg = BigInteger.valueOf(g);
		BigInteger aa = BigInteger.valueOf(a);
		BigInteger bb = BigInteger.valueOf(b);
		return aa.multiply(bb).divide(gg);
	}

	static boolean nextPermutation(int[] a) {
		for(int i = a.length - 2; i >= 0; --i) {
			if(a[i] < a[i+1]) {
				for(int j = a.length - 1; ; --j) {
					if(a[i] < a[j]) {
						int t = a[i];
						a[i] = a[j];
						a[j] = t;
						for(i++, j = a.length - 1; i < j; ++i, --j) {
							t = a[i];
							a[i] = a[j];
							a[j] = t;
						}
						return true;
					}
				}
			}
		}
		return false;
	}

	static void shuffle(Object[] a) {
		Random r = new Random();
		for(int i = a.length - 1; i > 0; --i) {
			int si = r.nextInt(i);
			Object t = a[si];
			a[si] = a[i];
			a[i] = t;
		}
	}

	static void shuffle(int[] a) {
		Random r = new Random();
		for(int i = a.length - 1; i > 0; --i) {
			int si = r.nextInt(i);
			int t = a[si];
			a[si] = a[i];
			a[i] = t;
		}
	}

	static void shuffle(long[] a) {
		Random r = new Random();
		for(int i = a.length - 1; i > 0; --i) {
			int si = r.nextInt(i);
			long t = a[si];
			a[si] = a[i];
			a[i] = t;
		}
	}

	static int lower_bound(int[] a, int n, int k) {
		int s = 0;
		int e = n;
		int m;
		while (e - s > 0) {
			m = (s + e) / 2;
			if (a[m] < k)
				s = m + 1;
			else
				e = m;
		}
		return e;
	}
	static int lower_bound(long[] a, int n, long k) {
		int s = 0;
		int e = n;
		int m;
		while (e - s > 0) {
			m = (s + e) / 2;
			if (a[m] < k)
				s = m + 1;
			else
				e = m;
		}
		return e;
	}

	static int gcd(int a, int b) {
		return b == 0 ? a : gcd(b, a % b);
	}
	static long gcd(long a, long b) {
		return b == 0 ? a : gcd(b, a % b);
	}
	static BigInteger gcd(BigInteger a, BigInteger b) {
		return b.compareTo(BigInteger.ZERO) == 0 ? a : gcd(b, a.mod(b));
	}

	static class Pair implements Comparable<Pair> {
		int first, second;

		public Pair(int first, int second) {
			super();
			this.first = first;
			this.second = second;
		}

		@Override
		public int compareTo(Pair o) {
			return this.first != o.first ? this.first - o.first : this.second - o.second;
		}

//		@Override
//		public int compareTo(Pair o) {
//			return this.first != o.first ? o.first - this.first : o.second - this.second;
//		}

		@Override
		public int hashCode() {
			final int prime = 31;
			int result = 1;
			result = prime * result + first;
			result = prime * result + second;
			return result;
		}

		@Override
		public boolean equals(Object obj) {
			if (this == obj)
				return true;
			if (obj == null)
				return false;
			if (getClass() != obj.getClass())
				return false;
			Pair other = (Pair) obj;
			if (first != other.first)
				return false;
			if (second != other.second)
				return false;
			return true;
		}
	}
}

class InputReader {

	private final InputStream stream;
	private final byte[] buf = new byte[8192];
	private int curChar, snumChars;

	public InputReader(InputStream st) {
		this.stream = st;
	}

	public int read() {
		if (snumChars == -1)
			throw new InputMismatchException();
		if (curChar >= snumChars) {
			curChar = 0;
			try {
				snumChars = stream.read(buf);
			} catch (IOException e) {
				throw new InputMismatchException();
			}
			if (snumChars <= 0)
				return -1;
		}
		return buf[curChar++];
	}

	public int nextInt() {
		int c = read();
		while (isSpaceChar(c)) {
			c = read();
		}
		int sgn = 1;
		if (c == '-') {
			sgn = -1;
			c = read();
		}
		int res = 0;
		do {
			res *= 10;
			res += c - '0';
			c = read();
		} while (!isSpaceChar(c));
		return res * sgn;
	}

	public long nextLong() {
		int c = read();
		while (isSpaceChar(c)) {
			c = read();
		}
		int sgn = 1;
		if (c == '-') {
			sgn = -1;
			c = read();
		}
		long res = 0;
		do {
			res *= 10;
			res += c - '0';
			c = read();
		} while (!isSpaceChar(c));
		return res * sgn;
	}

	public int[] nextIntArray(int n) {
		int a[] = new int[n];
		for (int i = 0; i < n; i++) {
			a[i] = nextInt();
		}
		return a;
	}

	public String readString() {
		int c = read();
		while (isSpaceChar(c)) {
			c = read();
		}
		StringBuilder res = new StringBuilder();
		do {
			res.appendCodePoint(c);
			c = read();
		} while (!isSpaceChar(c));
		return res.toString();
	}

	public String nextLine() {
		int c = read();
		while (isSpaceChar(c))
			c = read();
		StringBuilder res = new StringBuilder();
		do {
			res.appendCodePoint(c);
			c = read();
		} while (!isEndOfLine(c));
		return res.toString();
	}

	public boolean isSpaceChar(int c) {
		return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
	}

	private boolean isEndOfLine(int c) {
		return c == '\n' || c == '\r' || c == -1;
	}

}

import java.io.*;
import java.math.BigInteger;
import java.util.*;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Stream;

public class E_educational_32
{
	public static final long[] POWER2 = generatePOWER2();
	public static final IteratorBuffer<Long> ITERATOR_BUFFER_PRIME = new IteratorBuffer<>(streamPrime(1000000).iterator());
	private static BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
	private static StringTokenizer stringTokenizer = null;
	private static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));

	static class Array<Type> implements Iterable<Type>
	{
		private final Object[] array;

		public Array(int size)
		{
			this.array = new Object[size];
		}

		public Array(int size, Type element)
		{
			this(size);
			Arrays.fill(this.array, element);
		}

		public Array(Array<Type> array, Type element)
		{
			this(array.size() + 1);
			for (int index = 0; index < array.size(); index++)
			{
				set(index, array.get(index));
			}
			set(size() - 1, element);
		}

		public Array(List<Type> list)
		{
			this(list.size());
			int index = 0;
			for (Type element : list)
			{
				set(index, element);
				index += 1;
			}
		}

		public Type get(int index)
		{
			return (Type) this.array[index];
		}

		@Override
		public Iterator<Type> iterator()
		{
			return new Iterator<Type>()
			{
				int index = 0;

				@Override
				public boolean hasNext()
				{
					return this.index < size();
				}

				@Override
				public Type next()
				{
					Type result = Array.this.get(index);
					index += 1;
					return result;
				}
			};
		}

		public Array set(int index, Type value)
		{
			this.array[index] = value;
			return this;
		}

		public int size()
		{
			return this.array.length;
		}

		public List<Type> toList()
		{
			List<Type> result = new ArrayList<>();
			for (Type element : this)
			{
				result.add(element);
			}
			return result;
		}

		@Override
		public String toString()
		{
			return "[" + E_educational_32.toString(this, ", ") + "]";
		}
	}

	static class BIT
	{
		private static int lastBit(int index)
		{
			return index & -index;
		}

		private final long[] tree;

		public BIT(int size)
		{
			this.tree = new long[size];
		}

		public void add(int index, long delta)
		{
			index += 1;
			while (index <= this.tree.length)
			{
				tree[index - 1] += delta;
				index += lastBit(index);
			}
		}

		private long prefix(int end)
		{
			long result = 0;
			while (end > 0)
			{
				result += this.tree[end - 1];
				end -= lastBit(end);
			}
			return result;
		}

		public int size()
		{
			return this.tree.length;
		}

		public long sum(int start, int end)
		{
			return prefix(end) - prefix(start);
		}
	}

	static abstract class Edge<TypeVertex extends Vertex<TypeVertex, TypeEdge>, TypeEdge extends Edge<TypeVertex, TypeEdge>>
	{
		public final TypeVertex vertex0;
		public final TypeVertex vertex1;
		public final boolean bidirectional;

		public Edge(TypeVertex vertex0, TypeVertex vertex1, boolean bidirectional)
		{
			this.vertex0 = vertex0;
			this.vertex1 = vertex1;
			this.bidirectional = bidirectional;
			this.vertex0.edges.add(getThis());
			if (this.bidirectional)
			{
				this.vertex1.edges.add(getThis());
			}
		}

		public abstract TypeEdge getThis();

		public TypeVertex other(Vertex<TypeVertex, TypeEdge> vertex)
		{
			TypeVertex result;
			if (vertex0 == vertex)
			{
				result = vertex1;
			}
			else
			{
				result = vertex0;
			}
			return result;
		}

		public void remove()
		{
			this.vertex0.edges.remove(getThis());
			if (this.bidirectional)
			{
				this.vertex1.edges.remove(getThis());
			}
		}

		@Override
		public String toString()
		{
			return this.vertex0 + "->" + this.vertex1;
		}
	}

	public static class EdgeDefault<TypeVertex extends Vertex<TypeVertex, EdgeDefault<TypeVertex>>> extends Edge<TypeVertex, EdgeDefault<TypeVertex>>
	{
		public EdgeDefault(TypeVertex vertex0, TypeVertex vertex1, boolean bidirectional)
		{
			super(vertex0, vertex1, bidirectional);
		}

		@Override
		public EdgeDefault<TypeVertex> getThis()
		{
			return this;
		}
	}

	public static class EdgeDefaultDefault extends Edge<VertexDefaultDefault, EdgeDefaultDefault>
	{
		public EdgeDefaultDefault(VertexDefaultDefault vertex0, VertexDefaultDefault vertex1, boolean bidirectional)
		{
			super(vertex0, vertex1, bidirectional);
		}

		@Override
		public EdgeDefaultDefault getThis()
		{
			return this;
		}
	}

	public static class FIFO<Type>
	{
		public SingleLinkedList<Type> start;
		public SingleLinkedList<Type> end;

		public FIFO()
		{
			this.start = null;
			this.end = null;
		}

		public boolean isEmpty()
		{
			return this.start == null;
		}

		public Type peek()
		{
			return this.start.element;
		}

		public Type pop()
		{
			Type result = this.start.element;
			this.start = this.start.next;
			return result;
		}

		public void push(Type element)
		{
			SingleLinkedList<Type> list = new SingleLinkedList<>(element, null);
			if (this.start == null)
			{
				this.start = list;
				this.end = list;
			}
			else
			{
				this.end.next = list;
				this.end = list;
			}
		}
	}

	static class Fraction implements Comparable<Fraction>
	{
		public static final Fraction ZERO = new Fraction(0, 1);

		public static Fraction fraction(long whole)
		{
			return fraction(whole, 1);
		}

		public static Fraction fraction(long numerator, long denominator)
		{
			Fraction result;
			if (denominator == 0)
			{
				throw new ArithmeticException();
			}
			if (numerator == 0)
			{
				result = Fraction.ZERO;
			}
			else
			{
				int sign;
				if (numerator < 0 ^ denominator < 0)
				{
					sign = -1;
					numerator = Math.abs(numerator);
					denominator = Math.abs(denominator);
				}
				else
				{
					sign = 1;
				}
				long gcd = gcd(numerator, denominator);
				result = new Fraction(sign * numerator / gcd, denominator / gcd);
			}
			return result;
		}

		public final long numerator;
		public final long denominator;

		private Fraction(long numerator, long denominator)
		{
			this.numerator = numerator;
			this.denominator = denominator;
		}

		public Fraction add(Fraction fraction)
		{
			return fraction(this.numerator * fraction.denominator + fraction.numerator * this.denominator, this.denominator * fraction.denominator);
		}

		@Override
		public int compareTo(Fraction that)
		{
			return Long.compare(this.numerator * that.denominator, that.numerator * this.denominator);
		}

		public Fraction divide(Fraction fraction)
		{
			return multiply(fraction.inverse());
		}

		public boolean equals(Fraction that)
		{
			return this.compareTo(that) == 0;
		}

		public boolean equals(Object that)
		{
			return this.compareTo((Fraction) that) == 0;
		}

		public Fraction getRemainder()
		{
			return fraction(this.numerator - getWholePart() * denominator, denominator);
		}

		public long getWholePart()
		{
			return this.numerator / this.denominator;
		}

		public Fraction inverse()
		{
			return fraction(this.denominator, this.numerator);
		}

		public Fraction multiply(Fraction fraction)
		{
			return fraction(this.numerator * fraction.numerator, this.denominator * fraction.denominator);
		}

		public Fraction neg()
		{
			return fraction(-this.numerator, this.denominator);
		}

		public Fraction sub(Fraction fraction)
		{
			return add(fraction.neg());
		}

		@Override
		public String toString()
		{
			String result;
			if (getRemainder().equals(Fraction.ZERO))
			{
				result = "" + this.numerator;
			}
			else
			{
				result = this.numerator + "/" + this.denominator;
			}
			return result;
		}
	}

	static class IteratorBuffer<Type>
	{
		private Iterator<Type> iterator;
		private List<Type> list;

		public IteratorBuffer(Iterator<Type> iterator)
		{
			this.iterator = iterator;
			this.list = new ArrayList<Type>();
		}

		public Iterator<Type> iterator()
		{
			return new Iterator<Type>()
			{
				int index = 0;

				@Override
				public boolean hasNext()
				{
					return this.index < list.size() || IteratorBuffer.this.iterator.hasNext();
				}

				@Override
				public Type next()
				{
					if (list.size() <= this.index)
					{
						list.add(iterator.next());
					}
					Type result = list.get(index);
					index += 1;
					return result;
				}
			};
		}
	}

	public static class MapCount<Type> extends SortedMapAVL<Type, Long>
	{
		private int count;

		public MapCount(Comparator<? super Type> comparator)
		{
			super(comparator);
			this.count = 0;
		}

		public long add(Type key, Long delta)
		{
			long result;
			if (delta > 0)
			{
				Long value = get(key);
				if (value == null)
				{
					value = delta;
				}
				else
				{
					value += delta;
				}
				put(key, value);
				result = delta;
			}
			else
			{
				result = 0;
			}
			this.count += result;
			return result;
		}

		public int count()
		{
			return this.count;
		}

		public List<Type> flatten()
		{
			List<Type> result = new ArrayList<>();
			for (Entry<Type, Long> entry : entrySet())
			{
				for (long index = 0; index < entry.getValue(); index++)
				{
					result.add(entry.getKey());
				}
			}
			return result;
		}

		@Override
		public SortedMapAVL<Type, Long> headMap(Type keyEnd)
		{
			throw new UnsupportedOperationException();
		}

		@Override
		public void putAll(Map<? extends Type, ? extends Long> map)
		{
			throw new UnsupportedOperationException();
		}

		public long remove(Type key, Long delta)
		{
			long result;
			if (delta > 0)
			{
				Long value = get(key) - delta;
				if (value <= 0)
				{
					result = delta + value;
					remove(key);
				}
				else
				{
					result = delta;
					put(key, value);
				}
			}
			else
			{
				result = 0;
			}
			this.count -= result;
			return result;
		}

		@Override
		public Long remove(Object key)
		{
			Long result = super.remove(key);
			this.count -= result;
			return result;
		}

		@Override
		public SortedMapAVL<Type, Long> subMap(Type keyStart, Type keyEnd)
		{
			throw new UnsupportedOperationException();
		}

		@Override
		public SortedMapAVL<Type, Long> tailMap(Type keyStart)
		{
			throw new UnsupportedOperationException();
		}
	}

	public static class MapSet<TypeKey, TypeValue> extends SortedMapAVL<TypeKey, SortedSetAVL<TypeValue>> implements Iterable<TypeValue>
	{
		private Comparator<? super TypeValue> comparatorValue;

		public MapSet(Comparator<? super TypeKey> comparatorKey, Comparator<? super TypeValue> comparatorValue)
		{
			super(comparatorKey);
			this.comparatorValue = comparatorValue;
		}

		public MapSet(Comparator<? super TypeKey> comparatorKey, SortedSetAVL<Entry<TypeKey, SortedSetAVL<TypeValue>>> entrySet, Comparator<? super TypeValue> comparatorValue)
		{
			super(comparatorKey, entrySet);
			this.comparatorValue = comparatorValue;
		}

		public boolean add(TypeKey key, TypeValue value)
		{
			SortedSetAVL<TypeValue> set = computeIfAbsent(key, k -> new SortedSetAVL<>(comparatorValue));
			return set.add(value);
		}

		public TypeValue firstValue()
		{
			TypeValue result;
			Entry<TypeKey, SortedSetAVL<TypeValue>> firstEntry = firstEntry();
			if (firstEntry == null)
			{
				result = null;
			}
			else
			{
				result = firstEntry.getValue().first();
			}
			return result;
		}

		@Override
		public MapSet<TypeKey, TypeValue> headMap(TypeKey keyEnd)
		{
			return new MapSet<>(this.comparator, this.entrySet.headSet(new AbstractMap.SimpleEntry<>(keyEnd, null)), this.comparatorValue);
		}

		public Iterator<TypeValue> iterator()
		{
			return new Iterator<TypeValue>()
			{
				Iterator<SortedSetAVL<TypeValue>> iteratorValues = values().iterator();
				Iterator<TypeValue> iteratorValue = null;

				@Override
				public boolean hasNext()
				{
					return iteratorValues.hasNext() || (iteratorValue != null && iteratorValue.hasNext());
				}

				@Override
				public TypeValue next()
				{
					if (iteratorValue == null || !iteratorValue.hasNext())
					{
						iteratorValue = iteratorValues.next().iterator();
					}
					return iteratorValue.next();
				}
			};
		}

		public TypeValue lastValue()
		{
			TypeValue result;
			Entry<TypeKey, SortedSetAVL<TypeValue>> lastEntry = lastEntry();
			if (lastEntry == null)
			{
				result = null;
			}
			else
			{
				result = lastEntry.getValue().last();
			}
			return result;
		}

		public boolean removeSet(TypeKey key, TypeValue value)
		{
			boolean result;
			SortedSetAVL<TypeValue> set = get(key);
			if (set == null)
			{
				result = false;
			}
			else
			{
				result = set.remove(value);
				if (set.size() == 0)
				{
					remove(key);
				}
			}
			return result;
		}

		@Override
		public MapSet<TypeKey, TypeValue> tailMap(TypeKey keyStart)
		{
			return new MapSet<>(this.comparator, this.entrySet.tailSet(new AbstractMap.SimpleEntry<>(keyStart, null)), this.comparatorValue);
		}
	}

	public static class Matrix
	{
		public final int rows;
		public final int columns;
		public final Fraction[][] cells;

		public Matrix(int rows, int columns)
		{
			this.rows = rows;
			this.columns = columns;
			this.cells = new Fraction[rows][columns];
			for (int row = 0; row < rows; row++)
			{
				for (int column = 0; column < columns; column++)
				{
					set(row, column, Fraction.ZERO);
				}
			}
		}

		public void add(int rowSource, int rowTarget, Fraction fraction)
		{
			for (int column = 0; column < columns; column++)
			{
				this.cells[rowTarget][column] = this.cells[rowTarget][column].add(this.cells[rowSource][column].multiply(fraction));
			}
		}

		private int columnPivot(int row)
		{
			int result = this.columns;
			for (int column = this.columns - 1; 0 <= column; column--)
			{
				if (this.cells[row][column].compareTo(Fraction.ZERO) != 0)
				{
					result = column;
				}
			}
			return result;
		}

		public void reduce()
		{
			for (int rowMinimum = 0; rowMinimum < this.rows; rowMinimum++)
			{
				int rowPivot = rowPivot(rowMinimum);
				if (rowPivot != -1)
				{
					int columnPivot = columnPivot(rowPivot);
					Fraction current = this.cells[rowMinimum][columnPivot];
					Fraction pivot = this.cells[rowPivot][columnPivot];
					Fraction fraction = pivot.inverse().sub(current.divide(pivot));
					add(rowPivot, rowMinimum, fraction);
					for (int row = rowMinimum + 1; row < this.rows; row++)
					{
						if (columnPivot(row) == columnPivot)
						{
							add(rowMinimum, row, this.cells[row][columnPivot(row)].neg());
						}
					}
				}
			}
		}

		private int rowPivot(int rowMinimum)
		{
			int result = -1;
			int pivotColumnMinimum = this.columns;
			for (int row = rowMinimum; row < this.rows; row++)
			{
				int pivotColumn = columnPivot(row);
				if (pivotColumn < pivotColumnMinimum)
				{
					result = row;
					pivotColumnMinimum = pivotColumn;
				}
			}
			return result;
		}

		public void set(int row, int column, Fraction value)
		{
			this.cells[row][column] = value;
		}

		public String toString()
		{
			String result = "";
			for (int row = 0; row < rows; row++)
			{
				for (int column = 0; column < columns; column++)
				{
					result += this.cells[row][column] + "\t";
				}
				result += "\n";
			}
			return result;
		}
	}

	public static class Node<Type>
	{
		public static <Type> Node<Type> balance(Node<Type> result)
		{
			while (result != null && 1 < Math.abs(height(result.left) - height(result.right)))
			{
				if (height(result.left) < height(result.right))
				{
					Node<Type> right = result.right;
					if (height(right.right) < height(right.left))
					{
						result = new Node<>(result.value, result.left, right.rotateRight());
					}
					result = result.rotateLeft();
				}
				else
				{
					Node<Type> left = result.left;
					if (height(left.left) < height(left.right))
					{
						result = new Node<>(result.value, left.rotateLeft(), result.right);
					}
					result = result.rotateRight();
				}
			}
			return result;
		}

		public static <Type> Node<Type> clone(Node<Type> result)
		{
			if (result != null)
			{
				result = new Node<>(result.value, clone(result.left), clone(result.right));
			}
			return result;
		}

		public static <Type> Node<Type> delete(Node<Type> node, Type value, Comparator<? super Type> comparator)
		{
			Node<Type> result;
			if (node == null)
			{
				result = null;
			}
			else
			{
				int compare = comparator.compare(value, node.value);
				if (compare == 0)
				{
					if (node.left == null)
					{
						result = node.right;
					}
					else
					{
						if (node.right == null)
						{
							result = node.left;
						}
						else
						{
							Node<Type> first = first(node.right);
							result = new Node<>(first.value, node.left, delete(node.right, first.value, comparator));
						}
					}
				}
				else
				{
					if (compare < 0)
					{
						result = new Node<>(node.value, delete(node.left, value, comparator), node.right);
					}
					else
					{
						result = new Node<>(node.value, node.left, delete(node.right, value, comparator));
					}
				}
				result = balance(result);
			}
			return result;
		}

		public static <Type> Node<Type> first(Node<Type> result)
		{
			while (result.left != null)
			{
				result = result.left;
			}
			return result;
		}

		public static <Type> Node<Type> get(Node<Type> node, Type value, Comparator<? super Type> comparator)
		{
			Node<Type> result;
			if (node == null)
			{
				result = null;
			}
			else
			{
				int compare = comparator.compare(value, node.value);
				if (compare == 0)
				{
					result = node;
				}
				else
				{
					if (compare < 0)
					{
						result = get(node.left, value, comparator);
					}
					else
					{
						result = get(node.right, value, comparator);
					}
				}
			}
			return result;
		}

		public static <Type> Node<Type> head(Node<Type> node, Type value, Comparator<? super Type> comparator)
		{
			Node<Type> result;
			if (node == null)
			{
				result = null;
			}
			else
			{
				int compare = comparator.compare(value, node.value);
				if (compare == 0)
				{
					result = node.left;
				}
				else
				{
					if (compare < 0)
					{
						result = head(node.left, value, comparator);
					}
					else
					{
						result = new Node<>(node.value, node.left, head(node.right, value, comparator));
					}
				}
				result = balance(result);
			}
			return result;
		}

		public static int height(Node node)
		{
			return node == null ? 0 : node.height;
		}

		public static <Type> Node<Type> insert(Node<Type> node, Type value, Comparator<? super Type> comparator)
		{
			Node<Type> result;
			if (node == null)
			{
				result = new Node<>(value, null, null);
			}
			else
			{
				int compare = comparator.compare(value, node.value);
				if (compare == 0)
				{
					result = new Node<>(value, node.left, node.right);
					;
				}
				else
				{
					if (compare < 0)
					{
						result = new Node<>(node.value, insert(node.left, value, comparator), node.right);
					}
					else
					{
						result = new Node<>(node.value, node.left, insert(node.right, value, comparator));
					}
				}
				result = balance(result);
			}
			return result;
		}

		public static <Type> Node<Type> last(Node<Type> result)
		{
			while (result.right != null)
			{
				result = result.right;
			}
			return result;
		}

		public static int size(Node node)
		{
			return node == null ? 0 : node.size;
		}

		public static <Type> Node<Type> tail(Node<Type> node, Type value, Comparator<? super Type> comparator)
		{
			Node<Type> result;
			if (node == null)
			{
				result = null;
			}
			else
			{
				int compare = comparator.compare(value, node.value);
				if (compare == 0)
				{
					result = new Node<>(node.value, null, node.right);
				}
				else
				{
					if (compare < 0)
					{
						result = new Node<>(node.value, tail(node.left, value, comparator), node.right);
					}
					else
					{
						result = tail(node.right, value, comparator);
					}
				}
				result = balance(result);
			}
			return result;
		}

		public static <Type> void traverseOrderIn(Node<Type> node, Consumer<Type> consumer)
		{
			if (node != null)
			{
				traverseOrderIn(node.left, consumer);
				consumer.accept(node.value);
				traverseOrderIn(node.right, consumer);
			}
		}

		public final Type value;
		public final Node<Type> left;
		public final Node<Type> right;
		public final int size;
		private final int height;

		public Node(Type value, Node<Type> left, Node<Type> right)
		{
			this.value = value;
			this.left = left;
			this.right = right;
			this.size = 1 + size(left) + size(right);
			this.height = 1 + Math.max(height(left), height(right));
		}

		public Node<Type> rotateLeft()
		{
			Node<Type> left = new Node<>(this.value, this.left, this.right.left);
			return new Node<>(this.right.value, left, this.right.right);
		}

		public Node<Type> rotateRight()
		{
			Node<Type> right = new Node<>(this.value, this.left.right, this.right);
			return new Node<>(this.left.value, this.left.left, right);
		}
	}

	public static class SingleLinkedList<Type>
	{
		public final Type element;
		public SingleLinkedList<Type> next;

		public SingleLinkedList(Type element, SingleLinkedList<Type> next)
		{
			this.element = element;
			this.next = next;
		}

		public void toCollection(Collection<Type> collection)
		{
			if (this.next != null)
			{
				this.next.toCollection(collection);
			}
			collection.add(this.element);
		}
	}

	public static class SmallSetIntegers
	{
		public static final int SIZE = 20;
		public static final int[] SET = generateSet();
		public static final int[] COUNT = generateCount();
		public static final int[] INTEGER = generateInteger();

		private static int count(int set)
		{
			int result = 0;
			for (int integer = 0; integer < SIZE; integer++)
			{
				if (0 < (set & set(integer)))
				{
					result += 1;
				}
			}
			return result;
		}

		private static final int[] generateCount()
		{
			int[] result = new int[1 << SIZE];
			for (int set = 0; set < result.length; set++)
			{
				result[set] = count(set);
			}
			return result;
		}

		private static final int[] generateInteger()
		{
			int[] result = new int[1 << SIZE];
			Arrays.fill(result, -1);
			for (int integer = 0; integer < SIZE; integer++)
			{
				result[SET[integer]] = integer;
			}
			return result;
		}

		private static final int[] generateSet()
		{
			int[] result = new int[SIZE];
			for (int integer = 0; integer < result.length; integer++)
			{
				result[integer] = set(integer);
			}
			return result;
		}

		private static int set(int integer)
		{
			return 1 << integer;
		}
	}

	public static class SortedMapAVL<TypeKey, TypeValue> implements SortedMap<TypeKey, TypeValue>
	{
		public final Comparator<? super TypeKey> comparator;
		public final SortedSetAVL<Entry<TypeKey, TypeValue>> entrySet;

		public SortedMapAVL(Comparator<? super TypeKey> comparator)
		{
			this(comparator, new SortedSetAVL<>((entry0, entry1) -> comparator.compare(entry0.getKey(), entry1.getKey())));
		}

		private SortedMapAVL(Comparator<? super TypeKey> comparator, SortedSetAVL<Entry<TypeKey, TypeValue>> entrySet)
		{
			this.comparator = comparator;
			this.entrySet = entrySet;
		}

		@Override
		public void clear()
		{
			this.entrySet.clear();
		}

		@Override
		public Comparator<? super TypeKey> comparator()
		{
			return this.comparator;
		}

		@Override
		public boolean containsKey(Object key)
		{
			return this.entrySet().contains(new AbstractMap.SimpleEntry<>((TypeKey) key, null));
		}

		@Override
		public boolean containsValue(Object value)
		{
			throw new UnsupportedOperationException();
		}

		@Override
		public SortedSetAVL<Entry<TypeKey, TypeValue>> entrySet()
		{
			return this.entrySet;
		}

		public Entry<TypeKey, TypeValue> firstEntry()
		{
			return this.entrySet.first();
		}

		@Override
		public TypeKey firstKey()
		{
			return firstEntry().getKey();
		}

		@Override
		public TypeValue get(Object key)
		{
			Entry<TypeKey, TypeValue> entry = new AbstractMap.SimpleEntry<>((TypeKey) key, null);
			entry = this.entrySet.get(entry);
			return entry == null ? null : entry.getValue();
		}

		@Override
		public SortedMapAVL<TypeKey, TypeValue> headMap(TypeKey keyEnd)
		{
			return new SortedMapAVL<>(this.comparator, this.entrySet.headSet(new AbstractMap.SimpleEntry<>(keyEnd, null)));
		}

		@Override
		public boolean isEmpty()
		{
			return this.entrySet.isEmpty();
		}

		@Override
		public Set<TypeKey> keySet()
		{
			return new SortedSet<TypeKey>()
			{
				@Override
				public boolean add(TypeKey typeKey)
				{
					throw new UnsupportedOperationException();
				}

				@Override
				public boolean addAll(Collection<? extends TypeKey> collection)
				{
					throw new UnsupportedOperationException();
				}

				@Override
				public void clear()
				{
					throw new UnsupportedOperationException();
				}

				@Override
				public Comparator<? super TypeKey> comparator()
				{
					throw new UnsupportedOperationException();
				}

				@Override
				public boolean contains(Object o)
				{
					throw new UnsupportedOperationException();
				}

				@Override
				public boolean containsAll(Collection<?> collection)
				{
					throw new UnsupportedOperationException();
				}

				@Override
				public TypeKey first()
				{
					throw new UnsupportedOperationException();
				}

				@Override
				public SortedSet<TypeKey> headSet(TypeKey typeKey)
				{
					throw new UnsupportedOperationException();
				}

				@Override
				public boolean isEmpty()
				{
					return size() == 0;
				}

				@Override
				public Iterator<TypeKey> iterator()
				{
					final Iterator<Entry<TypeKey, TypeValue>> iterator = SortedMapAVL.this.entrySet.iterator();
					return new Iterator<TypeKey>()
					{
						@Override
						public boolean hasNext()
						{
							return iterator.hasNext();
						}

						@Override
						public TypeKey next()
						{
							return iterator.next().getKey();
						}
					};
				}

				@Override
				public TypeKey last()
				{
					throw new UnsupportedOperationException();
				}

				@Override
				public boolean remove(Object o)
				{
					throw new UnsupportedOperationException();
				}

				@Override
				public boolean removeAll(Collection<?> collection)
				{
					throw new UnsupportedOperationException();
				}

				@Override
				public boolean retainAll(Collection<?> collection)
				{
					throw new UnsupportedOperationException();
				}

				@Override
				public int size()
				{
					return SortedMapAVL.this.entrySet.size();
				}

				@Override
				public SortedSet<TypeKey> subSet(TypeKey typeKey, TypeKey e1)
				{
					throw new UnsupportedOperationException();
				}

				@Override
				public SortedSet<TypeKey> tailSet(TypeKey typeKey)
				{
					throw new UnsupportedOperationException();
				}

				@Override
				public Object[] toArray()
				{
					throw new UnsupportedOperationException();
				}

				@Override
				public <T> T[] toArray(T[] ts)
				{
					throw new UnsupportedOperationException();
				}
			};
		}

		public Entry<TypeKey, TypeValue> lastEntry()
		{
			return this.entrySet.last();
		}

		@Override
		public TypeKey lastKey()
		{
			return lastEntry().getKey();
		}

		@Override
		public TypeValue put(TypeKey key, TypeValue value)
		{
			TypeValue result = get(key);
			Entry<TypeKey, TypeValue> entry = new AbstractMap.SimpleEntry<>(key, value);
			this.entrySet().add(entry);
			return result;
		}

		@Override
		public void putAll(Map<? extends TypeKey, ? extends TypeValue> map)
		{
			map.entrySet()
					.forEach(entry -> put(entry.getKey(), entry.getValue()));
		}

		@Override
		public TypeValue remove(Object key)
		{
			TypeValue result = get(key);
			Entry<TypeKey, TypeValue> entry = new AbstractMap.SimpleEntry<>((TypeKey) key, null);
			this.entrySet.remove(entry);
			return result;
		}

		@Override
		public int size()
		{
			return this.entrySet().size();
		}

		@Override
		public SortedMapAVL<TypeKey, TypeValue> subMap(TypeKey keyStart, TypeKey keyEnd)
		{
			return new SortedMapAVL<>(this.comparator, this.entrySet.subSet(new AbstractMap.SimpleEntry<>(keyStart, null), new AbstractMap.SimpleEntry<>(keyEnd, null)));
		}

		@Override
		public SortedMapAVL<TypeKey, TypeValue> tailMap(TypeKey keyStart)
		{
			return new SortedMapAVL<>(this.comparator, this.entrySet.tailSet(new AbstractMap.SimpleEntry<>(keyStart, null)));
		}

		@Override
		public String toString()
		{
			return this.entrySet().toString();
		}

		@Override
		public Collection<TypeValue> values()
		{
			return new Collection<TypeValue>()
			{
				@Override
				public boolean add(TypeValue typeValue)
				{
					throw new UnsupportedOperationException();
				}

				@Override
				public boolean addAll(Collection<? extends TypeValue> collection)
				{
					throw new UnsupportedOperationException();
				}

				@Override
				public void clear()
				{
					throw new UnsupportedOperationException();
				}

				@Override
				public boolean contains(Object value)
				{
					throw new UnsupportedOperationException();
				}

				@Override
				public boolean containsAll(Collection<?> collection)
				{
					throw new UnsupportedOperationException();
				}

				@Override
				public boolean isEmpty()
				{
					return SortedMapAVL.this.entrySet.isEmpty();
				}

				@Override
				public Iterator<TypeValue> iterator()
				{
					return new Iterator<TypeValue>()
					{
						Iterator<Entry<TypeKey, TypeValue>> iterator = SortedMapAVL.this.entrySet.iterator();

						@Override
						public boolean hasNext()
						{
							return this.iterator.hasNext();
						}

						@Override
						public TypeValue next()
						{
							return this.iterator.next().getValue();
						}
					};
				}

				@Override
				public boolean remove(Object o)
				{
					throw new UnsupportedOperationException();
				}

				@Override
				public boolean removeAll(Collection<?> collection)
				{
					throw new UnsupportedOperationException();
				}

				@Override
				public boolean retainAll(Collection<?> collection)
				{
					throw new UnsupportedOperationException();
				}

				@Override
				public int size()
				{
					return SortedMapAVL.this.entrySet.size();
				}

				@Override
				public Object[] toArray()
				{
					throw new UnsupportedOperationException();
				}

				@Override
				public <T> T[] toArray(T[] ts)
				{
					throw new UnsupportedOperationException();
				}
			};
		}
	}

	public static class SortedSetAVL<Type> implements SortedSet<Type>
	{
		public Comparator<? super Type> comparator;
		public Node<Type> root;

		private SortedSetAVL(Comparator<? super Type> comparator, Node<Type> root)
		{
			this.comparator = comparator;
			this.root = root;
		}

		public SortedSetAVL(Comparator<? super Type> comparator)
		{
			this(comparator, null);
		}

		public SortedSetAVL(Collection<? extends Type> collection, Comparator<? super Type> comparator)
		{
			this(comparator, null);
			this.addAll(collection);
		}

		public SortedSetAVL(SortedSetAVL<Type> sortedSetAVL)
		{
			this(sortedSetAVL.comparator, Node.clone(sortedSetAVL.root));
		}

		@Override
		public boolean add(Type value)
		{
			int sizeBefore = size();
			this.root = Node.insert(this.root, value, this.comparator);
			return sizeBefore != size();
		}

		@Override
		public boolean addAll(Collection<? extends Type> collection)
		{
			return collection.stream()
					.map(this::add)
					.reduce(true, (x, y) -> x | y);
		}

		@Override
		public void clear()
		{
			this.root = null;
		}

		@Override
		public Comparator<? super Type> comparator()
		{
			return this.comparator;
		}

		@Override
		public boolean contains(Object value)
		{
			return Node.get(this.root, (Type) value, this.comparator) != null;
		}

		@Override
		public boolean containsAll(Collection<?> collection)
		{
			return collection.stream()
					.allMatch(this::contains);
		}

		@Override
		public Type first()
		{
			return Node.first(this.root).value;
		}

		public Type get(Type value)
		{
			Node<Type> node = Node.get(this.root, value, this.comparator);
			return node == null ? null : node.value;
		}

		@Override
		public SortedSetAVL<Type> headSet(Type valueEnd)
		{
			return new SortedSetAVL<>(this.comparator, Node.head(this.root, valueEnd, this.comparator));
		}

		@Override
		public boolean isEmpty()
		{
			return this.root == null;
		}

		@Override
		public Iterator<Type> iterator()
		{
			Stack<Node<Type>> path = new Stack<>();
			return new Iterator<Type>()
			{
				{
					push(SortedSetAVL.this.root);
				}

				@Override
				public boolean hasNext()
				{
					return !path.isEmpty();
				}

				@Override
				public Type next()
				{
					if (path.isEmpty())
					{
						throw new NoSuchElementException();
					}
					else
					{
						Node<Type> node = path.peek();
						Type result = node.value;
						if (node.right != null)
						{
							push(node.right);
						}
						else
						{
							do
							{
								node = path.pop();
							}
							while (!path.isEmpty() && path.peek().right == node);
						}
						return result;
					}
				}

				public void push(Node<Type> node)
				{
					while (node != null)
					{
						path.push(node);
						node = node.left;
					}
				}
			};
		}

		@Override
		public Type last()
		{
			return Node.last(this.root).value;
		}

		@Override
		public boolean remove(Object value)
		{
			int sizeBefore = size();
			this.root = Node.delete(this.root, (Type) value, this.comparator);
			return sizeBefore != size();
		}

		@Override
		public boolean removeAll(Collection<?> collection)
		{
			return collection.stream()
					.map(this::remove)
					.reduce(true, (x, y) -> x | y);
		}

		@Override
		public boolean retainAll(Collection<?> collection)
		{
			SortedSetAVL<Type> set = new SortedSetAVL<>(this.comparator);
			collection.stream()
					.map(element -> (Type) element)
					.filter(this::contains)
					.forEach(set::add);
			boolean result = size() != set.size();
			this.root = set.root;
			return result;
		}

		@Override
		public int size()
		{
			return this.root == null ? 0 : this.root.size;
		}

		@Override
		public SortedSetAVL<Type> subSet(Type valueStart, Type valueEnd)
		{
			return tailSet(valueStart).headSet(valueEnd);
		}

		@Override
		public SortedSetAVL<Type> tailSet(Type valueStart)
		{
			return new SortedSetAVL<>(this.comparator, Node.tail(this.root, valueStart, this.comparator));
		}

		@Override
		public Object[] toArray()
		{
			return toArray(new Object[0]);
		}

		@Override
		public <T> T[] toArray(T[] ts)
		{
			List<Object> list = new ArrayList<>();
			Node.traverseOrderIn(this.root, list::add);
			return list.toArray(ts);
		}

		@Override
		public String toString()
		{
			return "{" + E_educational_32.toString(this, ", ") + "}";
		}
	}

	public static class Tree2D
	{
		public static final int SIZE = 1 << 30;
		public static final Tree2D[] TREES_NULL = new Tree2D[] { null, null, null, null };

		public static boolean contains(int x, int y, int left, int bottom, int size)
		{
			return left <= x && x < left + size && bottom <= y && y < bottom + size;
		}

		public static int count(Tree2D[] trees)
		{
			int result = 0;
			for (int index = 0; index < 4; index++)
			{
				if (trees[index] != null)
				{
					result += trees[index].count;
				}
			}
			return result;
		}

		public static int count
				(
						int rectangleLeft,
						int rectangleBottom,
						int rectangleRight,
						int rectangleTop,
						Tree2D tree,
						int left,
						int bottom,
						int size
				)
		{
			int result;
			if (tree == null)
			{
				result = 0;
			}
			else
			{
				int right = left + size;
				int top = bottom + size;
				int intersectionLeft = Math.max(rectangleLeft, left);
				int intersectionBottom = Math.max(rectangleBottom, bottom);
				int intersectionRight = Math.min(rectangleRight, right);
				int intersectionTop = Math.min(rectangleTop, top);
				if (intersectionRight <= intersectionLeft || intersectionTop <= intersectionBottom)
				{
					result = 0;
				}
				else
				{
					if (intersectionLeft == left && intersectionBottom == bottom && intersectionRight == right && intersectionTop == top)
					{
						result = tree.count;
					}
					else
					{
						size = size >> 1;
						result = 0;
						for (int index = 0; index < 4; index++)
						{
							result += count
									(
											rectangleLeft,
											rectangleBottom,
											rectangleRight,
											rectangleTop,
											tree.trees[index],
											quadrantLeft(left, size, index),
											quadrantBottom(bottom, size, index),
											size
									);
						}
					}
				}
			}
			return result;
		}

		public static int quadrantBottom(int bottom, int size, int index)
		{
			return bottom + (index >> 1) * size;
		}

		public static int quadrantLeft(int left, int size, int index)
		{
			return left + (index & 1) * size;
		}

		public final Tree2D[] trees;
		public final int count;

		private Tree2D(Tree2D[] trees, int count)
		{
			this.trees = trees;
			this.count = count;
		}

		public Tree2D(Tree2D[] trees)
		{
			this(trees, count(trees));
		}

		public Tree2D()
		{
			this(TREES_NULL);
		}

		public int count(int rectangleLeft, int rectangleBottom, int rectangleRight, int rectangleTop)
		{
			return count
					(
							rectangleLeft,
							rectangleBottom,
							rectangleRight,
							rectangleTop,
							this,
							0,
							0,
							SIZE
					);
		}

		public Tree2D setPoint
				(
						int x,
						int y,
						Tree2D tree,
						int left,
						int bottom,
						int size
				)
		{
			Tree2D result;
			if (contains(x, y, left, bottom, size))
			{
				if (size == 1)
				{
					result = new Tree2D(TREES_NULL, 1);
				}
				else
				{
					size = size >> 1;
					Tree2D[] trees = new Tree2D[4];
					for (int index = 0; index < 4; index++)
					{
						trees[index] = setPoint
								(
										x,
										y,
										tree == null ? null : tree.trees[index],
										quadrantLeft(left, size, index),
										quadrantBottom(bottom, size, index),
										size
								);
					}
					result = new Tree2D(trees);
				}
			}
			else
			{
				result = tree;
			}
			return result;
		}

		public Tree2D setPoint(int x, int y)
		{
			return setPoint
					(
							x,
							y,
							this,
							0,
							0,
							SIZE
					);
		}
	}

	public static class Tuple2<Type0, Type1>
	{
		public final Type0 v0;
		public final Type1 v1;

		public Tuple2(Type0 v0, Type1 v1)
		{
			this.v0 = v0;
			this.v1 = v1;
		}

		@Override
		public String toString()
		{
			return "(" + this.v0 + ", " + this.v1 + ")";
		}
	}

	public static class Tuple2Comparable<Type0 extends Comparable<? super Type0>, Type1 extends Comparable<? super Type1>> extends Tuple2<Type0, Type1> implements Comparable<Tuple2Comparable<Type0, Type1>>
	{
		public Tuple2Comparable(Type0 v0, Type1 v1)
		{
			super(v0, v1);
		}

		@Override
		public int compareTo(Tuple2Comparable<Type0, Type1> that)
		{
			int result = this.v0.compareTo(that.v0);
			if (result == 0)
			{
				result = this.v1.compareTo(that.v1);
			}
			return result;
		}
	}

	public static class Tuple3<Type0, Type1, Type2>
	{
		public final Type0 v0;
		public final Type1 v1;
		public final Type2 v2;

		public Tuple3(Type0 v0, Type1 v1, Type2 v2)
		{
			this.v0 = v0;
			this.v1 = v1;
			this.v2 = v2;
		}

		@Override
		public String toString()
		{
			return "(" + this.v0 + ", " + this.v1 + ", " + this.v2 + ")";
		}
	}

	public static class Vertex
			<
					TypeVertex extends Vertex<TypeVertex, TypeEdge>,
					TypeEdge extends Edge<TypeVertex, TypeEdge>
					>
			implements Comparable<Vertex<? super TypeVertex, ? super TypeEdge>>
	{
		public static <
				TypeVertex extends Vertex<TypeVertex, TypeEdge>,
				TypeEdge extends Edge<TypeVertex, TypeEdge>,
				TypeResult
				> TypeResult breadthFirstSearch
				(
						TypeVertex vertex,
						TypeEdge edge,
						BiFunctionResult<TypeVertex, TypeEdge, TypeResult> function,
						Array<Boolean> visited,
						FIFO<TypeVertex> verticesNext,
						FIFO<TypeEdge> edgesNext,
						TypeResult result
				)
		{
			if (!visited.get(vertex.index))
			{
				visited.set(vertex.index, true);
				result = function.apply(vertex, edge, result);
				for (TypeEdge edgeNext : vertex.edges)
				{
					TypeVertex vertexNext = edgeNext.other(vertex);
					if (!visited.get(vertexNext.index))
					{
						verticesNext.push(vertexNext);
						edgesNext.push(edgeNext);
					}
				}
			}
			return result;
		}

		public static <
				TypeVertex extends Vertex<TypeVertex, TypeEdge>,
				TypeEdge extends Edge<TypeVertex, TypeEdge>,
				TypeResult
				>
		TypeResult breadthFirstSearch
				(
						Array<TypeVertex> vertices,
						int indexVertexStart,
						BiFunctionResult<TypeVertex, TypeEdge, TypeResult> function,
						TypeResult result
				)
		{
			Array<Boolean> visited = new Array<>(vertices.size(), false);
			FIFO<TypeVertex> verticesNext = new FIFO<>();
			verticesNext.push(vertices.get(indexVertexStart));
			FIFO<TypeEdge> edgesNext = new FIFO<>();
			edgesNext.push(null);
			while (!verticesNext.isEmpty())
			{
				result = breadthFirstSearch(verticesNext.pop(), edgesNext.pop(), function, visited, verticesNext, edgesNext, result);
			}
			return result;
		}

		public static <
				TypeVertex extends Vertex<TypeVertex, TypeEdge>,
				TypeEdge extends Edge<TypeVertex, TypeEdge>
				>
		boolean
		cycle
				(
						TypeVertex start,
						SortedSet<TypeVertex> result
				)
		{
			boolean cycle = false;
			Stack<TypeVertex> stackVertex = new Stack<>();
			Stack<TypeEdge> stackEdge = new Stack<>();
			stackVertex.push(start);
			stackEdge.push(null);
			while (!stackVertex.isEmpty())
			{
				TypeVertex vertex = stackVertex.pop();
				TypeEdge edge = stackEdge.pop();
				if (!result.contains(vertex))
				{
					result.add(vertex);
					for (TypeEdge otherEdge : vertex.edges)
					{
						if (otherEdge != edge)
						{
							TypeVertex otherVertex = otherEdge.other(vertex);
							if (result.contains(otherVertex))
							{
								cycle = true;
							}
							else
							{
								stackVertex.push(otherVertex);
								stackEdge.push(otherEdge);
							}
						}
					}
				}
			}
			return cycle;
		}

		public static <
				TypeVertex extends Vertex<TypeVertex, TypeEdge>,
				TypeEdge extends Edge<TypeVertex, TypeEdge>
				>
		SortedSet<TypeVertex>
		depthFirstSearch
				(
						TypeVertex start,
						BiConsumer<TypeVertex, TypeEdge> functionVisitPre,
						BiConsumer<TypeVertex, TypeEdge> functionVisitPost
				)
		{
			SortedSet<TypeVertex> result = new SortedSetAVL<>(Comparator.naturalOrder());
			Stack<TypeVertex> stackVertex = new Stack<>();
			Stack<TypeEdge> stackEdge = new Stack<>();
			stackVertex.push(start);
			stackEdge.push(null);
			while (!stackVertex.isEmpty())
			{
				TypeVertex vertex = stackVertex.pop();
				TypeEdge edge = stackEdge.pop();
				if (result.contains(vertex))
				{
					functionVisitPost.accept(vertex, edge);
				}
				else
				{
					result.add(vertex);
					stackVertex.push(vertex);
					stackEdge.push(edge);
					functionVisitPre.accept(vertex, edge);
					for (TypeEdge otherEdge : vertex.edges)
					{
						TypeVertex otherVertex = otherEdge.other(vertex);
						if (!result.contains(otherVertex))
						{
							stackVertex.push(otherVertex);
							stackEdge.push(otherEdge);
						}
					}
				}
			}
			return result;
		}

		public static <
				TypeVertex extends Vertex<TypeVertex, TypeEdge>,
				TypeEdge extends Edge<TypeVertex, TypeEdge>
				>
		SortedSet<TypeVertex>
		depthFirstSearch
				(
						TypeVertex start,
						Consumer<TypeVertex> functionVisitPreVertex,
						Consumer<TypeVertex> functionVisitPostVertex
				)
		{
			BiConsumer<TypeVertex, TypeEdge> functionVisitPreVertexEdge = (vertex, edge) ->
			{
				functionVisitPreVertex.accept(vertex);
			};
			BiConsumer<TypeVertex, TypeEdge> functionVisitPostVertexEdge = (vertex, edge) ->
			{
				functionVisitPostVertex.accept(vertex);
			};
			return depthFirstSearch(start, functionVisitPreVertexEdge, functionVisitPostVertexEdge);
		}

		public final int index;
		public final List<TypeEdge> edges;

		public Vertex(int index)
		{
			this.index = index;
			this.edges = new ArrayList<>();
		}

		@Override
		public int compareTo(Vertex<? super TypeVertex, ? super TypeEdge> that)
		{
			return Integer.compare(this.index, that.index);
		}

		@Override
		public String toString()
		{
			return "" + this.index;
		}
	}

	public static class VertexDefault<TypeEdge extends Edge<VertexDefault<TypeEdge>, TypeEdge>> extends Vertex<VertexDefault<TypeEdge>, TypeEdge>
	{
		public VertexDefault(int index)
		{
			super(index);
		}
	}

	public static class VertexDefaultDefault extends Vertex<VertexDefaultDefault, EdgeDefaultDefault>
	{
		public static Array<VertexDefaultDefault> vertices(int n)
		{
			Array<VertexDefaultDefault> result = new Array<>(n);
			for (int index = 0; index < n; index++)
			{
				result.set(index, new VertexDefaultDefault(index));
			}
			return result;
		}

		public VertexDefaultDefault(int index)
		{
			super(index);
		}
	}

	public static class Wrapper<Type>
	{
		public Type value;

		public Wrapper(Type value)
		{
			this.value = value;
		}

		public Type get()
		{
			return this.value;
		}

		public void set(Type value)
		{
			this.value = value;
		}

		@Override
		public String toString()
		{
			return this.value.toString();
		}
	}

	public static void add(int delta, int[] result)
	{
		for (int index = 0; index < result.length; index++)
		{
			result[index] += delta;
		}
	}

	public static void add(int delta, int[]... result)
	{
		for (int index = 0; index < result.length; index++)
		{
			add(delta, result[index]);
		}
	}

	public static int binarySearchMaximum(Function<Integer, Boolean> filter, int start, int end)
	{
		return -binarySearchMinimum(x -> filter.apply(-x), -end, -start);
	}

	public static int binarySearchMinimum(Function<Integer, Boolean> filter, int start, int end)
	{
		int result;
		if (start == end)
		{
			result = end;
		}
		else
		{
			int middle = start + (end - start) / 2;
			if (filter.apply(middle))
			{
				result = binarySearchMinimum(filter, start, middle);
			}
			else
			{
				result = binarySearchMinimum(filter, middle + 1, end);
			}
		}
		return result;
	}

	public static void close()
	{
		out.close();
	}

	public static List<List<Integer>> combinations(int n, int k)
	{
		List<List<Integer>> result = new ArrayList<>();
		if (k == 0)
		{
		}
		else
		{
			if (k == 1)
			{
				List<Integer> combination = new ArrayList<>();
				combination.add(n);
				result.add(combination);
			}
			else
			{
				for (int index = 0; index <= n; index++)
				{
					for (List<Integer> combination : combinations(n - index, k - 1))
					{
						combination.add(index);
						result.add(combination);
					}
				}
			}
		}
		return result;
	}

	public static <Type> int compare(Iterator<Type> iterator0, Iterator<Type> iterator1, Comparator<Type> comparator)
	{
		int result = 0;
		while (result == 0 && iterator0.hasNext() && iterator1.hasNext())
		{
			result = comparator.compare(iterator0.next(), iterator1.next());
		}
		if (result == 0)
		{
			if (iterator1.hasNext())
			{
				result = -1;
			}
			else
			{
				if (iterator0.hasNext())
				{
					result = 1;
				}
			}
		}
		return result;
	}

	public static <Type> int compare(Iterable<Type> iterable0, Iterable<Type> iterable1, Comparator<Type> comparator)
	{
		return compare(iterable0.iterator(), iterable1.iterator(), comparator);
	}

	public static long divideCeil(long x, long y)
	{
		return (x + y - 1) / y;
	}

	public static Set<Long> divisors(long n)
	{
		SortedSetAVL<Long> result = new SortedSetAVL<>(Comparator.naturalOrder());
		result.add(1L);
		for (Long factor : factors(n))
		{
			SortedSetAVL<Long> divisors = new SortedSetAVL<>(result);
			for (Long divisor : result)
			{
				divisors.add(divisor * factor);
			}
			result = divisors;
		}
		return result;
	}

	public static LinkedList<Long> factors(long n)
	{
		LinkedList<Long> result = new LinkedList<>();
		Iterator<Long> primes = ITERATOR_BUFFER_PRIME.iterator();
		Long prime;
		while (n > 1 && (prime = primes.next()) * prime <= n)
		{
			while (n % prime == 0)
			{
				result.add(prime);
				n /= prime;
			}
		}
		if (n > 1)
		{
			result.add(n);
		}
		return result;
	}

	public static long faculty(int n)
	{
		long result = 1;
		for (int index = 2; index <= n; index++)
		{
			result *= index;
		}
		return result;
	}

	public static long gcd(long a, long b)
	{
		while (a != 0 && b != 0)
		{
			if (a > b)
			{
				a %= b;
			}
			else
			{
				b %= a;
			}
		}
		return a + b;
	}

	public static long[] generatePOWER2()
	{
		long[] result = new long[63];
		for (int x = 0; x < result.length; x++)
		{
			result[x] = 1L << x;
		}
		return result;
	}

	public static boolean isPrime(long x)
	{
		boolean result = x > 1;
		Iterator<Long> iterator = ITERATOR_BUFFER_PRIME.iterator();
		Long prime;
		while ((prime = iterator.next()) * prime <= x)
		{
			result &= x % prime > 0;
		}
		return result;
	}

	public static long knapsack(List<Tuple3<Long, Integer, Integer>> itemsValueWeightCount, int weightMaximum)
	{
		long[] valuesMaximum = new long[weightMaximum + 1];
		for (Tuple3<Long, Integer, Integer> itemValueWeightCount : itemsValueWeightCount)
		{
			long itemValue = itemValueWeightCount.v0;
			int itemWeight = itemValueWeightCount.v1;
			int itemCount = itemValueWeightCount.v2;
			for (int weight = weightMaximum; 0 <= weight; weight--)
			{
				for (int index = 1; index <= itemCount && 0 <= weight - index * itemWeight; index++)
				{
					valuesMaximum[weight] = Math.max(valuesMaximum[weight], valuesMaximum[weight - index * itemWeight] + index * itemValue);
				}
			}
		}
		long result = 0;
		for (long valueMaximum : valuesMaximum)
		{
			result = Math.max(result, valueMaximum);
		}
		return result;
	}

	public static boolean knapsackPossible(List<Tuple2<Integer, Integer>> itemsWeightCount, int weightMaximum)
	{
		boolean[] weightPossible = new boolean[weightMaximum + 1];
		weightPossible[0] = true;
		int weightLargest = 0;
		for (Tuple2<Integer, Integer> itemWeightCount : itemsWeightCount)
		{
			int itemWeight = itemWeightCount.v0;
			int itemCount = itemWeightCount.v1;
			for (int weightStart = 0; weightStart < itemWeight; weightStart++)
			{
				int count = 0;
				for (int weight = weightStart; weight <= weightMaximum && (0 < count || weight <= weightLargest); weight += itemWeight)
				{
					if (weightPossible[weight])
					{
						count = itemCount;
					}
					else
					{
						if (0 < count)
						{
							weightPossible[weight] = true;
							weightLargest = weight;
							count -= 1;
						}
					}
				}
			}
		}
		return weightPossible[weightMaximum];
	}

	public static long lcm(int a, int b)
	{
		return a * b / gcd(a, b);
	}

	public static void main(String[] args)
	{
		try
		{
			solve();
		}
		catch (IOException exception)
		{
			exception.printStackTrace();
		}
		close();
	}

	public static double nextDouble() throws IOException
	{
		return Double.parseDouble(nextString());
	}

	public static int nextInt() throws IOException
	{
		return Integer.parseInt(nextString());
	}

	public static void nextInts(int n, int[]... result) throws IOException
	{
		for (int index = 0; index < n; index++)
		{
			for (int value = 0; value < result.length; value++)
			{
				result[value][index] = nextInt();
			}
		}
	}

	public static int[] nextInts(int n) throws IOException
	{
		int[] result = new int[n];
		nextInts(n, result);
		return result;
	}

	public static String nextLine() throws IOException
	{
		return bufferedReader.readLine();
	}

	public static long nextLong() throws IOException
	{
		return Long.parseLong(nextString());
	}

	public static void nextLongs(int n, long[]... result) throws IOException
	{
		for (int index = 0; index < n; index++)
		{
			for (int value = 0; value < result.length; value++)
			{
				result[value][index] = nextLong();
			}
		}
	}

	public static long[] nextLongs(int n) throws IOException
	{
		long[] result = new long[n];
		nextLongs(n, result);
		return result;
	}

	public static String nextString() throws IOException
	{
		while ((stringTokenizer == null) || (!stringTokenizer.hasMoreTokens()))
		{
			stringTokenizer = new StringTokenizer(bufferedReader.readLine());
		}
		return stringTokenizer.nextToken();
	}

	public static String[] nextStrings(int n) throws IOException
	{
		String[] result = new String[n];
		{
			for (int index = 0; index < n; index++)
			{
				result[index] = nextString();
			}
		}
		return result;
	}

	public static <T> List<T> permutation(long p, List<T> x)
	{
		List<T> copy = new ArrayList<>();
		for (int index = 0; index < x.size(); index++)
		{
			copy.add(x.get(index));
		}
		List<T> result = new ArrayList<>();
		for (int indexTo = 0; indexTo < x.size(); indexTo++)
		{
			int indexFrom = (int) p % copy.size();
			p = p / copy.size();
			result.add(copy.remove(indexFrom));
		}
		return result;
	}

	public static <Type> List<List<Type>> permutations(List<Type> list)
	{
		List<List<Type>> result = new ArrayList<>();
		result.add(new ArrayList<>());
		for (Type element : list)
		{
			List<List<Type>> permutations = result;
			result = new ArrayList<>();
			for (List<Type> permutation : permutations)
			{
				for (int index = 0; index <= permutation.size(); index++)
				{
					List<Type> permutationNew = new ArrayList<>(permutation);
					permutationNew.add(index, element);
					result.add(permutationNew);
				}
			}
		}
		return result;
	}

	public static Stream<BigInteger> streamFibonacci()
	{
		return Stream.generate(new Supplier<BigInteger>()
		{
			private BigInteger n0 = BigInteger.ZERO;
			private BigInteger n1 = BigInteger.ONE;

			@Override
			public BigInteger get()
			{
				BigInteger result = n0;
				n0 = n1;
				n1 = result.add(n0);
				return result;
			}
		});
	}

	public static Stream<Long> streamPrime(int sieveSize)
	{
		return Stream.generate(new Supplier<Long>()
		{
			private boolean[] isPrime = new boolean[sieveSize];
			private long sieveOffset = 2;
			private List<Long> primes = new ArrayList<>();
			private int index = 0;

			public void filter(long prime, boolean[] result)
			{
				if (prime * prime < this.sieveOffset + sieveSize)
				{
					long remainingStart = this.sieveOffset % prime;
					long start = remainingStart == 0 ? 0 : prime - remainingStart;
					for (long index = start; index < sieveSize; index += prime)
					{
						result[(int) index] = false;
					}
				}
			}

			public void generatePrimes()
			{
				Arrays.fill(this.isPrime, true);
				this.primes.forEach(prime -> filter(prime, isPrime));
				for (int index = 0; index < sieveSize; index++)
				{
					if (isPrime[index])
					{
						this.primes.add(this.sieveOffset + index);
						filter(this.sieveOffset + index, isPrime);
					}
				}
				this.sieveOffset += sieveSize;
			}

			@Override
			public Long get()
			{
				while (this.primes.size() <= this.index)
				{
					generatePrimes();
				}
				Long result = this.primes.get(this.index);
				this.index += 1;
				return result;
			}
		});
	}

	public static <Type> String toString(Iterator<Type> iterator, String separator)
	{
		StringBuilder stringBuilder = new StringBuilder();
		if (iterator.hasNext())
		{
			stringBuilder.append(iterator.next());
		}
		while (iterator.hasNext())
		{
			stringBuilder.append(separator);
			stringBuilder.append(iterator.next());
		}
		return stringBuilder.toString();
	}

	public static <Type> String toString(Iterator<Type> iterator)
	{
		return toString(iterator, " ");
	}

	public static <Type> String toString(Iterable<Type> iterable, String separator)
	{
		return toString(iterable.iterator(), separator);
	}

	public static <Type> String toString(Iterable<Type> iterable)
	{
		return toString(iterable, " ");
	}

	public static long totient(long n)
	{
		Set<Long> factors = new SortedSetAVL<>(factors(n), Comparator.naturalOrder());
		long result = n;
		for (long p : factors)
		{
			result -= result / p;
		}
		return result;
	}

	interface BiFunctionResult<Type0, Type1, TypeResult>
	{
		TypeResult apply(Type0 x0, Type1 x1, TypeResult x2);
	}

	public static List<Integer> combinations(int m, int start, int end, int[] as)
	{
		SortedSet<Integer> result = new TreeSet<>();
		result.add(0);
		for (int index = start; index < end; index++)
		{
			SortedSet<Integer> next = new TreeSet<>();
			next.addAll(result);
			for (Integer number : result)
			{
				next.add((number + as[index]) % m);
			}
			result = next;
		}
		return new ArrayList<>(result);
	}

	public static void solve() throws IOException
	{
		int n = nextInt();
		int m = nextInt();
		int[] as = nextInts(n);
		int half = n / 2;
		List<Integer> combinationsX = combinations(m, 0, half, as);
		List<Integer> combinationsY = combinations(m, half, n, as);
		int result = (combinationsX.get(combinationsX.size() - 1) + combinationsY.get(combinationsY.size() - 1)) % m;
		Collections.reverse(combinationsY);
		Iterator<Integer> iteratorY = combinationsY.iterator();
		Integer y = iteratorY.next();
		for (Integer x : combinationsX)
		{
			while (iteratorY.hasNext() && m <= x + y)
			{
				y = iteratorY.next();
			}
			if (x + y < m)
			{
				result = Math.max(result, x + y);
			}
		}
		out.println(result);
	}
}

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

public class Main {

	static InputReader in = new InputReader(System.in);
	static PrintWriter out = new PrintWriter(System.out);

	static int oo = (int)1e9;
//	static long oo = (long)1e15;
//	static int mod = 1_000_000_007;
	static int mod = 998244353;

	static int[] dx = {1, 0, -1, 0};
	static int[] dy = {0, -1, 0, 1};

	static int M = 5001;
	static double EPS = 1e-13;
	static int num = 1;

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

		int n = in.nextInt();
		int m = in.nextInt();
		int[] a = in.nextIntArray(n);
		if(n == 1) {
			int ans = a[0] % m;
			System.out.println(ans);
		}
		else {
			TreeSet<Integer> set1 = new TreeSet<>();
			TreeSet<Integer> set2 = new TreeSet<>();
			makeSet(set1, a, m, 0, n / 2, 0);
			makeSet(set2, a, m, n / 2 + 1, n-1, 0);
			int ans = 0;
			for(int i : set1) {
				Integer j = set2.lower(m - i);
				if(j == null) {
					j = set2.last();
				}
				int cur = (i + j) % m;
				ans = Math.max(ans, cur);
			}
			System.out.println(ans);
		}

		out.close();
	}

	static void makeSet(TreeSet<Integer> set, int[] a, int m, int i, int to, int cur) {
		if(i > to) {
			set.add(cur);
			return;
		}
		makeSet(set, a, m, i+1, to, cur);
		makeSet(set, a, m, i+1, to, (cur + a[i]) % m);
	}

	static int find(int[] g, int x) {
		return g[x] = g[x] == x ? x : find(g, g[x]);
	}

	static void union(int[] g, int[] size, int x, int y) {
		x = find(g, x); y = find(g, y);
		if(x == y)
			return;
		if(size[x] < size[y]) {
			g[x] = y;
			size[y] += size[x];
		}
		else {
			g[y] = x;
			size[x] += size[y];
		}
	}

	static class Segment {
		Segment left, right;
		int size, minIdx;
//		int time, lazy;

		public Segment(int[] a, int l, int r) {
			super();
			if(l == r) {
				this.minIdx = l;
				this.size = 1;
				return;
			}
			int mid = (l + r) / 2;
			left = new Segment(a, l, mid);
			right = new Segment(a, mid+1, r);
			if(a[left.minIdx] <= a[right.minIdx])
				this.minIdx = left.minIdx;
			else
				this.minIdx = right.minIdx;
			this.size = left.size + right.size;
		}

		boolean covered(int ll, int rr, int l, int r) {
			return ll <= l && rr >= r;
		}

		boolean noIntersection(int ll, int rr, int l, int r) {
			return ll > r || rr < l;
		}

//		void lazyPropagation() {
//			if(lazy != 0) {
//				if(left != null) {
//					left.setLazy(this.time, this.lazy);
//					right.setLazy(this.time, this.lazy);
//				}
//				else {
//					val = lazy;
//				}
//			}
//		}

//		void setLazy(int time, int lazy) {
//			if(this.time != 0 && this.time <= time)
//				return;
//			this.time = time;
//			this.lazy = lazy;
//		}

		int querySize(int ll, int rr, int l, int r) {
//			lazyPropagation();
			if(noIntersection(ll, rr, l, r))
				return 0;
			if(covered(ll, rr, l, r))
				return size;
			int mid = (l + r) / 2;
			int leftSize = left.querySize(ll, rr, l, mid);
			int rightSize = right.querySize(ll, rr, mid+1, r);
			return leftSize + rightSize;
		}

		int query(int k, int l, int r) {
			Segment trace = this;
			while(l < r) {
				int mid = (l + r) / 2;
				if(trace.left.size > k) {
					trace = trace.left;
					r = mid;
				}
				else {
					k -= trace.left.size;
					trace = trace.right;
					l = mid + 1;
				}
			}
			return l;
		}

		void update(int ll, int rr, int l, int r) {
//			lazyPropagation();
			if(noIntersection(ll, rr, l, r))
				return;
			if(covered(ll, rr, l, r)) {
//				setLazy(time, knight);
				this.minIdx = -1;
				this.size = 0;
				return;
			}
			int mid = (l + r) / 2;
			left.update(ll, rr, l, mid);
			right.update(ll, rr, mid+1, r);
			this.size = left.size + right.size;
		}
	}

	static long pow(long a, long n, long mod) {
		if(n == 0)
			return 1;
		if(n % 2 == 1)
			return a * pow(a, n-1, mod) % mod;
		long x = pow(a, n / 2, mod);
		return x * x % mod;
	}

	static int[] getPi(char[] a) {
		int m = a.length;
		int j = 0;
		int[] pi = new int[m];
		for(int i = 1; i < m; ++i) {
			while(j > 0 && a[i] != a[j])
				j = pi[j-1];
			if(a[i] == a[j]) {
				pi[i] = j + 1;
				j++;
			}
		}
		return pi;
	}

	static long lcm(long a, long b) {
		return a * b / gcd(a, b);
	}

	static BigInteger lcm2(long a, long b) {
		long g = gcd(a, b);
		BigInteger gg = BigInteger.valueOf(g);
		BigInteger aa = BigInteger.valueOf(a);
		BigInteger bb = BigInteger.valueOf(b);
		return aa.multiply(bb).divide(gg);
	}

	static boolean nextPermutation(int[] a) {
		for(int i = a.length - 2; i >= 0; --i) {
			if(a[i] < a[i+1]) {
				for(int j = a.length - 1; ; --j) {
					if(a[i] < a[j]) {
						int t = a[i];
						a[i] = a[j];
						a[j] = t;
						for(i++, j = a.length - 1; i < j; ++i, --j) {
							t = a[i];
							a[i] = a[j];
							a[j] = t;
						}
						return true;
					}
				}
			}
		}
		return false;
	}

	static void shuffle(Object[] a) {
		Random r = new Random();
		for(int i = a.length - 1; i > 0; --i) {
			int si = r.nextInt(i);
			Object t = a[si];
			a[si] = a[i];
			a[i] = t;
		}
	}

	static void shuffle(int[] a) {
		Random r = new Random();
		for(int i = a.length - 1; i > 0; --i) {
			int si = r.nextInt(i);
			int t = a[si];
			a[si] = a[i];
			a[i] = t;
		}
	}

	static void shuffle(long[] a) {
		Random r = new Random();
		for(int i = a.length - 1; i > 0; --i) {
			int si = r.nextInt(i);
			long t = a[si];
			a[si] = a[i];
			a[i] = t;
		}
	}

	static int lower_bound(int[] a, int n, int k) {
		int s = 0;
		int e = n;
		int m;
		while (e - s > 0) {
			m = (s + e) / 2;
			if (a[m] < k)
				s = m + 1;
			else
				e = m;
		}
		return e;
	}
	static int lower_bound(long[] a, int n, long k) {
		int s = 0;
		int e = n;
		int m;
		while (e - s > 0) {
			m = (s + e) / 2;
			if (a[m] < k)
				s = m + 1;
			else
				e = m;
		}
		return e;
	}

	static int gcd(int a, int b) {
		return b == 0 ? a : gcd(b, a % b);
	}
	static long gcd(long a, long b) {
		return b == 0 ? a : gcd(b, a % b);
	}
	static BigInteger gcd(BigInteger a, BigInteger b) {
		return b.compareTo(BigInteger.ZERO) == 0 ? a : gcd(b, a.mod(b));
	}

	static class Pair implements Comparable<Pair> {
		int first, second;

		public Pair(int first, int second) {
			super();
			this.first = first;
			this.second = second;
		}

		@Override
		public int compareTo(Pair o) {
			return this.first != o.first ? this.first - o.first : this.second - o.second;
		}

//		@Override
//		public int compareTo(Pair o) {
//			return this.first != o.first ? o.first - this.first : o.second - this.second;
//		}

		@Override
		public int hashCode() {
			final int prime = 31;
			int result = 1;
			result = prime * result + first;
			result = prime * result + second;
			return result;
		}

		@Override
		public boolean equals(Object obj) {
			if (this == obj)
				return true;
			if (obj == null)
				return false;
			if (getClass() != obj.getClass())
				return false;
			Pair other = (Pair) obj;
			if (first != other.first)
				return false;
			if (second != other.second)
				return false;
			return true;
		}
	}
}

class InputReader {

	private final InputStream stream;
	private final byte[] buf = new byte[8192];
	private int curChar, snumChars;

	public InputReader(InputStream st) {
		this.stream = st;
	}

	public int read() {
		if (snumChars == -1)
			throw new InputMismatchException();
		if (curChar >= snumChars) {
			curChar = 0;
			try {
				snumChars = stream.read(buf);
			} catch (IOException e) {
				throw new InputMismatchException();
			}
			if (snumChars <= 0)
				return -1;
		}
		return buf[curChar++];
	}

	public int nextInt() {
		int c = read();
		while (isSpaceChar(c)) {
			c = read();
		}
		int sgn = 1;
		if (c == '-') {
			sgn = -1;
			c = read();
		}
		int res = 0;
		do {
			res *= 10;
			res += c - '0';
			c = read();
		} while (!isSpaceChar(c));
		return res * sgn;
	}

	public long nextLong() {
		int c = read();
		while (isSpaceChar(c)) {
			c = read();
		}
		int sgn = 1;
		if (c == '-') {
			sgn = -1;
			c = read();
		}
		long res = 0;
		do {
			res *= 10;
			res += c - '0';
			c = read();
		} while (!isSpaceChar(c));
		return res * sgn;
	}

	public int[] nextIntArray(int n) {
		int a[] = new int[n];
		for (int i = 0; i < n; i++) {
			a[i] = nextInt();
		}
		return a;
	}

	public String readString() {
		int c = read();
		while (isSpaceChar(c)) {
			c = read();
		}
		StringBuilder res = new StringBuilder();
		do {
			res.appendCodePoint(c);
			c = read();
		} while (!isSpaceChar(c));
		return res.toString();
	}

	public String nextLine() {
		int c = read();
		while (isSpaceChar(c))
			c = read();
		StringBuilder res = new StringBuilder();
		do {
			res.appendCodePoint(c);
			c = read();
		} while (!isEndOfLine(c));
		return res.toString();
	}

	public boolean isSpaceChar(int c) {
		return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
	}

	private boolean isEndOfLine(int c) {
		return c == '\n' || c == '\r' || c == -1;
	}

}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.List;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.TreeSet;
import java.io.InputStream;
import java.util.ArrayList;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author ankur
 */
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);
        ltimedec solver = new ltimedec();
        solver.solve(1, in, out);
        out.close();
    }

    static class ltimedec {
        long mod;
        int n;
        List<Long> li = new ArrayList<>();
        int[] ar;
        TreeSet<Long> li2 = new TreeSet<>();

        public void solve(int testNumber, InputReader in, PrintWriter out) {
            n = in.nextInt();
            mod = in.nextInt();
            ar = in.nextIntArray(n);
            subset(0, 0, n / 2);
            subset(n / 2, 0, n);
            long max = 0;
            //out.print();
            // System.out.println(li);
            //System.out.println(li2);

            for (int i = 0; i < li.size(); i++) {
                long val1 = mod - li.get(i) - 1;
                //System.out.println(val1);
                if (val1 >= li2.first()) {
                    long val2 = li2.floor(val1);
                    //  System.out.println(val2+"saff");
                    max = Math.max(max, (li.get(i) + val2) % mod);
                }
                max = Math.max(max, li.get(i));
            }
            max = Math.max(max, li2.last());
            out.println(max);

        }

        void subset(int pos, long sum, int last) {
            if (pos == n) {
                li2.add(sum);
                return;
            }
            if (pos >= last) {
                li.add(sum);
                return;
            }
            subset(pos + 1, sum, last);
            subset(pos + 1, (sum + ar[pos]) % mod, last);

        }

    }

    static class InputReader {
        private final InputStream stream;
        private final byte[] buf = new byte[8192];
        private int curChar;
        private int snumChars;

        public InputReader(InputStream st) {
            this.stream = st;
        }

        public int read() {
            if (snumChars == -1)
                throw new InputMismatchException();
            if (curChar >= snumChars) {
                curChar = 0;
                try {
                    snumChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (snumChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }

        public int nextInt() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public int[] nextIntArray(int n) {
            int a[] = new int[n];
            for (int i = 0; i < n; i++) {
                a[i] = nextInt();
            }
            return a;
        }

        public boolean isSpaceChar(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

    }
}

import java.util.*;
import java.awt.List;
import java.io.*;
import java.lang.*;
import java.lang.reflect.Array;
public  class c2
{

	public static int mod = (int)Math.pow(10, 9) + 7;

    public static void main(String[] args)
    {
        InputReader in = new InputReader(System.in);
        PrintWriter pw = new PrintWriter(System.out);

        // Code starts..

        int n = in.nextInt();
        long m = in.nextLong();
        long[] a = new long[n];
        ArrayList<Long> l1 = new ArrayList<>();
        ArrayList<Long> l2 = new ArrayList<>();

        for(int i=0; i<n; i++)
        {
        	a[i] = in.nextLong()%m;
        	if(i<n/2)
        		l1.add(a[i]);
        	else
        		l2.add(a[i]);
        }

        TreeSet<Long> set2 = new TreeSet<>();
        TreeSet<Long> set1 = new TreeSet<>();
        set1.add(0L);
        set2.add(0L);

        fun(set1, 0, l1, 0, m);
        fun(set2, 0, l2, 0, m);

        long ans = 0;
        for(long p: set1)
        {

        	long p2 = m - p -1;
        	if(set2.floor(p2) != null )
        	{
        		p2 = set2.floor(p2);
        		ans = Math.max(ans, p + p2);
        	}

        }

        pw.println(ans);

        // code ends...

        pw.flush();
        pw.close();
    }

    public static void fun(TreeSet<Long> set, int idx, ArrayList<Long> list, long sum, long m) {

    	if(idx==list.size())
    		return;
    	set.add((sum + list.get(idx))%m);
    	fun(set, idx+1, list, sum, m);
    	fun(set, idx+1, list, (sum+list.get(idx))%m, m);

    }

    public static void factSieve(int[] fact, long n)
    {

        for (int i = 2; i <= n; i += 2)
            fact[i] = 2;

        for (int i = 3; i <= n; i += 2) {
            if (fact[i] == 0) {
                fact[i] = i;

                for (int j = i; (long) j * i <= n; j++) {
                    fact[(int) ((long) i * j)] = i;
                }
            }
        }

        /*
         * int k = 1000; while(k!=1) { System.out.print(a[k]+" "); k /= a[k];
         *
         * }
         */
    }

    public static int gcd(int p2, int p22)
    {
        if (p2 == 0)
            return (int) p22;
        return gcd(p22 % p2, p2);
    }

    public static void nextGreater(long[] a, int[] ans)
    {

        Stack<Integer> stk = new Stack<>();
        stk.push(0);

        for (int i = 1; i < a.length; i++) {

            if (!stk.isEmpty()) {
                int s = stk.pop();
                while (a[s] < a[i]) {
                    ans[s] = i;
                    if (!stk.isEmpty())
                        s = stk.pop();
                    else
                        break;
                }
                if (a[s] >= a[i])
                    stk.push(s);
            }

            stk.push(i);

        }
        return;

    }

    public static void nextGreaterRev(long[] a, int[] ans)
    {

        int n = a.length;
        int[] pans = new int[n];
        Arrays.fill(pans, -1);
        long[] arev = new long[n];
        for (int i = 0; i < n; i++)
            arev[i] = a[n - 1 - i];

        Stack<Integer> stk = new Stack<>();
        stk.push(0);

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

            if (!stk.isEmpty()) {
                int s = stk.pop();
                while (arev[s] < arev[i]) {
                    pans[s] = n - i - 1;
                    if (!stk.isEmpty())
                        s = stk.pop();
                    else
                        break;
                }
                if (arev[s] >= arev[i])
                    stk.push(s);
            }

            stk.push(i);

        }

        // for(int i=0; i<n; i++)
        // System.out.print(pans[i]+" ");

        for (int i = 0; i < n; i++)
            ans[i] = pans[n - i - 1];

        return;

    }

    public static void nextSmaller(long[] a, int[] ans)
    {

        Stack<Integer> stk = new Stack<>();
        stk.push(0);

        for (int i = 1; i < a.length; i++) {

            if (!stk.isEmpty()) {
                int s = stk.pop();
                while (a[s] > a[i]) {
                    ans[s] = i;
                    if (!stk.isEmpty())
                        s = stk.pop();
                    else
                        break;
                }
                if (a[s] <= a[i])
                    stk.push(s);
            }

            stk.push(i);

        }
        return;

    }

    public static long lcm(int[] numbers)
    {
        long lcm = 1;
        int divisor = 2;
        while (true) {
            int cnt = 0;
            boolean divisible = false;
            for (int i = 0; i < numbers.length; i++) {
                if (numbers[i] == 0) {
                    return 0;
                } else if (numbers[i] < 0) {
                    numbers[i] = numbers[i] * (-1);
                }
                if (numbers[i] == 1) {
                    cnt++;
                }
                if (numbers[i] % divisor == 0) {
                    divisible = true;
                    numbers[i] = numbers[i] / divisor;
                }
            }
            if (divisible) {
                lcm = lcm * divisor;
            } else {
                divisor++;
            }
            if (cnt == numbers.length) {
                return lcm;
            }
        }
    }

    public static long fact(long n)
    {

        long factorial = 1;
        for (int i = 1; i <= n; i++) {
            factorial *= i;
        }
        return factorial;
    }

    public static long choose(long total, long choose)
    {
        if (total < choose)
            return 0;
        if (choose == 0 || choose == total)
            return 1;
        return (choose(total - 1, choose - 1) + choose(total - 1, choose)) % mod;
    }

    public static int[] suffle(int[] a, Random gen)
    {
        int n = a.length;
        for (int i = 0; i < n; i++) {
            int ind = gen.nextInt(n - i) + i;
            int temp = a[ind];
            a[ind] = a[i];
            a[i] = temp;
        }
        return a;
    }

    public static int[] sufflesort(int[] a)
    {
        int n = a.length;
        Random gen = new Random();
        for (int i = 0; i < n; i++) {
            int ind = gen.nextInt(n - i) + i;
            int temp = a[ind];
            a[ind] = a[i];
            a[i] = temp;
        }
        Arrays.sort(a);
        return a;
    }

    public static int floorSearch(int arr[], int low, int high, int x)
    {
        if (low > high)
            return -1;

        if (x > arr[high])
            return high;
        int mid = (low + high) / 2;

        if (mid > 0 && arr[mid - 1] < x && x < arr[mid])
            return mid - 1;

        if (x < arr[mid])
            return floorSearch(arr, low, mid - 1, x);

        return floorSearch(arr, mid + 1, high, x);
    }

    public static void swap(int a, int b) {
        int temp = a;
        a = b;
        b = temp;
    }

    public static ArrayList<Integer> primeFactorization(int n)
    {
        ArrayList<Integer> a = new ArrayList<Integer>();
        for (int i = 2; i * i <= n; i++) {
            while (n % i == 0) {
                a.add(i);
                n /= i;
            }
        }
        if (n != 1)
            a.add(n);
        return a;
    }

    public static void sieve(boolean[] isPrime, int n)
    {
        for (int i = 1; i < n; i++)
            isPrime[i] = true;

        isPrime[0] = false;
        isPrime[1] = false;

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

    public static int lowerbound(ArrayList<Long> net, long c2)
    {
        int i = Collections.binarySearch(net, c2);
        if (i < 0)
            i = -(i + 2);
        return i;

    }

    public static int lowerboundArray(int[] dis, int c2)
    {
        int i = Arrays.binarySearch(dis, c2);

        if (i < 0)
            i = -(i + 2);
        return i;

    }

    public static int uperbound(ArrayList<Integer> list, int c2)
    {
        int i = Collections.binarySearch(list, c2);
        if (i < 0)
            i = -(i + 1);
        return i;

    }

    public static int uperboundArray(int[] dis, int c2)
    {
        int i = Arrays.binarySearch(dis, c2);
        if (i < 0)
            i = -(i + 1);
        return i;

    }

    public static int GCD(int a, int b)
    {
        if (b == 0)
            return a;
        else
            return GCD(b, a % b);
    }

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

    public static int d1;
    public static int p1;
    public static int q1;

    public static void extendedEuclid(int A, int B)
    {
        if (B == 0) {
            d1 = A;
            p1 = 1;
            q1 = 0;
        } else {
            extendedEuclid(B, A % B);
            int temp = p1;
            p1 = q1;
            q1 = temp - (A / B) * q1;
        }
    }

    public static long LCM(long a, long b) {
        return (a * b) / GCD(a, b);
    }

    public static int LCM(int a, int b) {
        return (a * b) / GCD(a, b);
    }

    public static int binaryExponentiation(int x, int n) {
        int result = 1;
        while (n > 0) {
            if (n % 2 == 1)
                result = result * x;
            x = x * x;
            n = n / 2;
        }
        return result;
    }

    public static int[] countDer(int n) {
        int der[] = new int[n + 1];

        der[0] = 1;
        der[1] = 0;
        der[2] = 1;

        for (int i = 3; i <= n; ++i)
            der[i] = (i - 1) * (der[i - 1] + der[i - 2]);

        // Return result for n
        return der;
    }

    static long binomialCoeff(int n, int k) {
        long C[][] = new long[n + 1][k + 1];
        int i, j;

        // Calculate value of Binomial Coefficient in bottom up manner
        for (i = 0; i <= n; i++) {
            for (j = 0; j <= Math.min(i, k); j++) {
                // Base Cases
                if (j == 0 || j == i)
                    C[i][j] = 1;

                // Calculate value using previosly stored values
                else
                    C[i][j] = C[i - 1][j - 1] + C[i - 1][j];
            }
        }

        return C[n][k];
    }

    public static long binaryExponentiation(long x, long n) {
        long result = 1;
        while (n > 0) {
            if (n % 2 == 1)
                result = result * x;
            x = (x % mod * x % mod) % mod;
            n = n / 2;
        }
        return result;
    }

    public static int modularExponentiation(int x, int n, int M) {
        int result = 1;
        while (n > 0) {
            if (n % 2 == 1)
                result = (result * x) % M;
            x = (x * x) % M;
            n = n / 2;
        }
        return result;
    }

    public static long modularExponentiation(long x, long n, long M) {
        long result = 1;
        while (n > 0) {
            if (n % 2 == 1)
                result = (result * x) % M;
            x = (x * x) % M;
            n = n / 2;
        }
        return result;
    }

    public static int modInverse(int A, int M) {
        return modularExponentiation(A, M - 2, M);
    }

    public static long sie(long A, long M) {
        return modularExponentiation(A, M - 2, M);
    }

    public static boolean isPrime(int n) {

        if (n <= 1)
            return false;
        if (n <= 3)
            return true;

        if (n % 2 == 0 || n % 3 == 0)
            return false;

        for (int i = 5; i * i <= n; i = i + 6) {
            if (n % i == 0 || n % (i + 2) == 0)
                return false;
        }

        return true;
    }

    static class pair implements Comparable<pair>

    {
        Integer x, y;

        pair(int x, int y) {
            this.x = x;
            this.y = y;
        }

        public int compareTo(pair o) {
            int result = x.compareTo(o.x);
            if (result == 0)
                result = y.compareTo(o.y);

            return result;
        }

        public String toString() {
            return x + " " + y;
        }

        public boolean equals(Object o) {
            if (o instanceof pair) {
                pair p = (pair) o;
                return p.x == x && p.y == y;
            }
            return false;
        }

        public int hashCode() {
            return new Long(x).hashCode() * 31 + new Long(y).hashCode();
        }

    }

    static class triplet implements Comparable<triplet> {
        Integer x, y, z;

        triplet(int x, int y, int z) {
            this.x = x;
            this.y = y;
            this.z = z;
        }

        public int compareTo(triplet o) {
            int result = x.compareTo(o.x);
            if (result == 0)
                result = y.compareTo(o.y);
            if (result == 0)
                result = z.compareTo(o.z);

            return result;
        }

        public boolean equlas(Object o) {
            if (o instanceof triplet) {
                triplet p = (triplet) o;
                return x == p.x && y == p.y && z == p.z;
            }
            return false;
        }

        public String toString() {
            return x + " " + y + " " + z;
        }

        public int hashCode() {
            return new Long(x).hashCode() * 31 + new Long(y).hashCode() + new Long(z).hashCode();
        }
    }

    /*
     * static class node implements Comparable<node>
     *
     * { Integer x, y, z; node(int x,int y, int z) { this.x=x; this.y=y; this.z=z; }
     *
     * public int compareTo(pair o) { int result = x.compareTo(o.x); if(result==0)
     * result = y.compareTo(o.y); if(result==0) result = z.compareTo(z); return
     * result; }
     *
     * @Override public int compareTo(node o) { // TODO Auto-generated method stub
     * return 0; } }
     */

    static class InputReader
	{

		private final InputStream stream;
		private final byte[] buf = new byte[8192];
		private int curChar, snumChars;
		private SpaceCharFilter filter;

		public InputReader(InputStream stream)
		{
			this.stream = stream;
		}

		public int snext()
		{
			if (snumChars == -1)
				throw new InputMismatchException();
			if (curChar >= snumChars)
			{
				curChar = 0;
				try
				{
					snumChars = stream.read(buf);
				}
				catch (IOException e)
				{
					throw new InputMismatchException();
				}
				if (snumChars <= 0)
					return -1;
			}
			return buf[curChar++];
		}

		public int nextInt()
	    {
			int c = snext();
			while (isSpaceChar(c))
			{
				c = snext();
			}
			int sgn = 1;
			if (c == '-')
		    {
				sgn = -1;
				c = snext();
			}
			int res = 0;
			do
			{
				if (c < '0' || c > '9')
					throw new InputMismatchException();
				res *= 10;
				res += c - '0';
				c = snext();
			} while (!isSpaceChar(c));
			return res * sgn;
		}

		public long nextLong()
	    {
			int c = snext();
			while (isSpaceChar(c))
			{
				c = snext();
			}
			int sgn = 1;
			if (c == '-')
			{
				sgn = -1;
				c = snext();
			}
			long res = 0;
			do
			{
				if (c < '0' || c > '9')
					throw new InputMismatchException();
				res *= 10;
				res += c - '0';
				c = snext();
			} while (!isSpaceChar(c));
			return res * sgn;
		}

		public int[] nextIntArray(int n)
		{
			int a[] = new int[n];
			for (int i = 0; i < n; i++)
			{
				a[i] = nextInt();
			}
			return a;
		}

		public String readString()
	    {
			int c = snext();
			while (isSpaceChar(c))
			{
				c = snext();
			}
			StringBuilder res = new StringBuilder();
			do
			{
				res.appendCodePoint(c);
				c = snext();
			} while (!isSpaceChar(c));
			return res.toString();
		}

		public String nextLine()
		{
			int c = snext();
			while (isSpaceChar(c))
				c = snext();
			StringBuilder res = new StringBuilder();
			do
			{
				res.appendCodePoint(c);
				c = snext();
			} while (!isEndOfLine(c));
			return res.toString();
		}

		public boolean isSpaceChar(int c)
		{
			if (filter != null)
				return filter.isSpaceChar(c);
			return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
		}

		private boolean isEndOfLine(int c)
		{
			return c == '\n' || c == '\r' || c == -1;
		}

		public interface SpaceCharFilter
	    {
			public boolean isSpaceChar(int ch);
		}
	}

}

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)-1;
                  int u=Collections.binarySearch(al2,x);
                  if(u>=0)
                   t=m-1;
                  u=Math.abs(u+2);
                  if(u>=0 && u<al2.size())
                  t=Math.max(t,(al1.get(i)+al2.get(u))%m);
            }

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

            System.out.println(t);
      }
}

import java.util.*;
import java.io.*;
import java.math.*;
public class Solution{
    public static int[] make(int[] a,int n,int mod){
        int nt = (1<<n);
        int[] t = new int[nt];
        for(int i=0;i<nt;i++){
            char[] c = Integer.toBinaryString(i).toCharArray();
            int sum = 0;
            for(int j=0;j<c.length;j++){
                if(c[c.length-1-j]=='1'){
                    sum+=a[j];
                    sum%=mod;
                }
            }
            t[i] = sum;
        }
        return t;
    }
    public static void main(String[] args)throws IOException{
        BufferedReader br =  new BufferedReader(new InputStreamReader(System.in));
        PrintWriter out = new PrintWriter(System.out);
        StringTokenizer st = new StringTokenizer(br.readLine());
        int n = Integer.parseInt(st.nextToken());
        int m = Integer.parseInt(st.nextToken());
        st = new StringTokenizer(br.readLine());
        if(n==1){
            int t = Integer.parseInt(st.nextToken());
            t %= m;
            out.println(t);
        }else{
            int n1 = n/2;
            int n2 = n-n1;
            int[] a = new int[n1];
            int[] b = new int[n2];
            for(int i=0;i<n1;i++){
                a[i] = Integer.parseInt(st.nextToken())%m;
            }
            for(int i=n1;i<n;i++){
                b[i-n1] = Integer.parseInt(st.nextToken())%m;
            }
            int[] t1 = make(a,n1,m);
            int[] t2 = make(b,n2,m);
            n1 = (1<<n1);
            n2 = (1<<n2);
            Arrays.sort(t1);
            Arrays.sort(t2);
            int max = Math.max(t1[n1-1],t2[n2-1]);
            int i=0;
            for(int j=n2-1;j>=0;j--){
                while(i<n1&&t1[i]+t2[j]<m) i++;
                if(i>0) max = Math.max(max,t1[i-1]+t2[j]);
            }
            out.println(max);
        }
        out.flush();
   }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.TreeSet;
import java.io.InputStream;
/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        OutputWriter out = new OutputWriter(outputStream);
        TaskE solver = new TaskE();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskE {
        TreeSet<Integer> get(int[] a, int m) {
            TreeSet<Integer> res = new TreeSet<>();
            for (int mask = 0; mask < (1 << a.length); mask++) {
                long sum = 0;
                for (int i = 0; i < a.length; i++) {
                    if (((mask >> i) & 1) == 1) {
                        sum += a[i];
                    }
                }
                sum %= m;
                res.add((int) sum);
            }
            return res;
        }

        public void solve(int testNumber, InputReader in, OutputWriter out) {
            int n = in.readInt();
            int m = in.readInt();
            int[] a = IOUtils.readIntArray(in, n);
            int mid = (a.length + 1) / 2;
            TreeSet<Integer> left = get(Arrays.copyOfRange(a, 0, mid), m);
            TreeSet<Integer> right = get(Arrays.copyOfRange(a, mid, a.length), m);
            int res = 0;
            for (int val : left) {
                int want = m - val - 1;
                Integer best = right.floor(want);
                if (best != null) {
                    res = Math.max(res, val + best);
                }
                res = Math.max(res, (val + right.last()) % m);
            }
            out.printLine(res);
        }
    }
    static class OutputWriter {
        private final PrintWriter writer;

        public OutputWriter(OutputStream outputStream) {
            writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
        }

        public OutputWriter(Writer writer) {
            this.writer = new PrintWriter(writer);
        }

        public void close() {
            writer.close();
        }

        public void printLine(int i) {
            writer.println(i);
        }
    }
    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private InputReader.SpaceCharFilter filter;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars == -1) {
                throw new InputMismatchException();
            }
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (numChars <= 0) {
                    return -1;
                }
            }
            return buf[curChar++];
        }

        public int readInt() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9') {
                    throw new InputMismatchException();
                }
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public boolean isSpaceChar(int c) {
            if (filter != null) {
                return filter.isSpaceChar(c);
            }
            return isWhitespace(c);
        }

        public static boolean isWhitespace(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);
        }
    }
    static class IOUtils {
        public static int[] readIntArray(InputReader in, int size) {
            int[] array = new int[size];
            for (int i = 0; i < size; i++) {
                array[i] = in.readInt();
            }
            return array;
        }
    }
}

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

public class Main {
    static long sumA[] = new long[1000000], sumB[] = new long[1000000];
    static void calSum(long x[], long sum[], int n, int c) {
        for (int i = 0; i < (1<<n); i++) {
            long s = 0;
            for (int j = 0; j < n; j++) {
                if ((i & (1<<j)) > 0) {
                    s += x[j + c];
                }
            }
            sum[i] = s;
        }
    }

    static void solve() throws IOException {
        rl(); int n = ni2(); int m = ni2();
        long x[] = new long[n];
        rl(); for (int i = 0; i < n; i++) x[i] = nl2();
        calSum(x, sumA, n/2, 0);
        calSum(x, sumB, n - n/2, n/2);
        int sizeA = 1<<(n/2);
        int sizeB = 1<<(n - n/2);
        long A[] = new long[sizeA];
        System.arraycopy(sumA, 0, A, 0, sizeA);
        long B[] = new long[sizeB];
        System.arraycopy(sumB, 0, B, 0, sizeB);
        for (int i = 0; i < sizeA; i++) A[i] = A[i] % m;
        Arrays.sort(A);
        for (int i = 0; i < sizeB; i++) B[i] = B[i] % m;
        Arrays.sort(B);
        long max = 0;
        for (int i = 0; i < sizeA; i++) {
            int k = Arrays.binarySearch(B, m - 1 - A[i]);
            if (k >= 0) {
                max = m - 1;
                break;
            }
            k = - k - 1;
            if (k == 0) {
                max = Math.max(max, A[i] + B[sizeB - 1]);
            } else {
                max = Math.max(max, A[i] + B[k - 1]);
            }
        }
        ans.append(max).append('\n');
        output.write(ans.toString());
        output.flush();
        output.close();
    }

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

    static BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
    static BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out));
    static StringBuilder ans = new StringBuilder();
    static String line;
    static StringTokenizer stringTokenizer;

    static int ni1() throws IOException {
        return Integer.parseInt(input.readLine());
    }

    static int ni2() throws IOException {
        return Integer.parseInt(stringTokenizer.nextToken());
    }

    static long nl1() throws IOException {
        return Long.parseLong(input.readLine());
    }

    static long nl2() {
        return Long.parseLong(stringTokenizer.nextToken());
    }

    static void rl() throws IOException {
        stringTokenizer = new StringTokenizer(input.readLine());
    }
}

//package info.stochastic;//package info.stochastic;

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

public class E {

    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskE solver = new TaskE();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskE {
        Set<Integer> calcSets(int[] a, int m) {
            Set<Integer> ans = new HashSet<>();
            for (int i = 0; i < (1 << a.length); i++) {
                int set = 0;
                int index = 1;
                for (int j = 0; j < a.length; j++) {
                    if ((i & (index << j)) > 0) {
                        set += a[j];
                        set %= m;
                    }
                }
                ans.add(set % m);
            }
            return ans;
        }

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

            int leftSize = n / 2;
            int rightSize = n / 2 + n % 2;

            int[] al = new int[leftSize];
            int[] ar = new int[rightSize];

            for (int i = 0; i < leftSize; i++) {
                al[i] = in.nextInt();
            }

            for (int i = 0; i < rightSize; i++) {
                ar[i] = in.nextInt();
            }

            Set<Integer> leftSet = calcSets(al, m);
            Set<Integer> rightSet = calcSets(ar, m);
            Integer[] right = new Integer[rightSet.size()];
            rightSet.toArray(right);
            Arrays.sort(right);

            int ans = 0;
            for (int fromLeft: leftSet) {
                int l = 0;
                int r = right.length - 1;
                int max = 0;
                while (l <= r) {
                    int mid = (l + r) >> 1;
                    if ((fromLeft + right[mid]) < m) {
                        max = fromLeft + right[mid];
                        l = mid + 1;
                    } else {
                        r = mid - 1;
                    }
                }
                ans = Math.max(ans, max);
            }

            out.print(ans);
        }

    }

    static class InputReader {
        public BufferedReader reader;
        public StringTokenizer tokenizer;

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

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

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

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.util.TreeSet;

public class CF0888E_MaximumSubsequence {
	static class Scanner {
		BufferedReader br;
		StringTokenizer st;

		public Scanner() {
			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 void print(Object b) {
		System.out.print(b);
	}

	static void println(Object b) {
		System.out.println(b);
	}

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

	static int[] arr1;
	static int[] arr2;
	static TreeSet<Integer> set;
	static ArrayList<Integer> arr;
	static int m;

	static void dfs1(int i, int sum) {
		if (i == arr1.length) {
			set.add(sum);
			return;
		}
		dfs1(i + 1, sum);
		dfs1(i + 1, (sum + arr1[i]) % m);
	}

	static void dfs2(int i, int sum) {
		if (i == arr2.length) {
			arr.add(sum);
			return;
		}
		dfs2(i + 1, sum);
		dfs2(i + 1, (sum + arr2[i]) % m);
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner scanner = new Scanner();
		int n = scanner.nextInt();
		m = scanner.nextInt();
		int two = n / 2;
		if (n % 2 == 1)
			two++;
		arr1 = new int[n / 2];
		arr2 = new int[two];
		for (int i = 0; i < arr1.length; i++)
			arr1[i] = scanner.nextInt();
		for (int i = 0; i < arr2.length; i++)
			arr2[i] = scanner.nextInt();
		set = new TreeSet<Integer>();
		arr = new ArrayList<Integer>();
		dfs1(0, 0);
		dfs2(0, 0);

		int ans = 0;
		for (int i = 0; i < arr.size(); i++) {
			if(arr.get(i) != 0 && arr.get(i) %m == 0)
				continue;
			ans = Math.max(ans, (set.lower(m - arr.get(i)) + arr.get(i)) % m);
			ans = Math.max(ans, (set.lower(2 * m - arr.get(i)) + arr.get(i)) % m);
		}
		println(ans);
	}

}

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, int m) {
            Set<Integer> foo = new TreeSet<>();
            foo.add(0);
            for (int i = s; i < e; ++i) {
                Set<Integer> tmp = new HashSet<>();
                for (int val : foo) {
                    int newval = (val + a[i]) % m;
                    if (!foo.contains(newval)) {
                        tmp.add(newval);
                    }
                }
                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, m);
            List<Integer> right = solve(a, n / 2, n, m);

            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.io.*;
import java.util.StringTokenizer;
import java.util.TreeSet;

public class Main {
    public static void main(String[] args) throws IOException {
        Scanner sc = new Scanner(System.in);
        PrintWriter out = new PrintWriter(System.out);
        int n = sc.nextInt();
        int m = sc.nextInt();
        int k = n / 2;
        int l = n - k;
        int[] a1 = new int[k];
        int[] a2 = new int[l];
        for (int i = 0; i < k; i++)
            a1[i] = sc.nextInt();
        for (int i = 0; i < l; i++)
            a2[i] = sc.nextInt();
        TreeSet<Integer> one = getAns(a1, k, m);
        TreeSet<Integer> two = getAns(a2, l, m);
        int max = 0;
        for (int num : one) {
            int allowed = m-num;
            Integer found = two.lower(allowed);
            if (found!=null) max = Math.max(max,found+num);
        }
        out.println(max);
        out.flush();
        out.close();
    }

    static TreeSet<Integer> getAns(int[] a, int n, int m) {
        TreeSet<Integer> ans = new TreeSet<>();
        for (int mask = 0; mask < (1 << n); mask++) {
            int sum = 0;
            for (int i = 0; i < n; i++) {
                if ((mask & (1 << i)) != 0) sum = (sum + a[i]) % m;
            }
            ans.add(sum);
        }

        return ans;

    }

    static class Scanner {
        StringTokenizer st;
        BufferedReader br;

        public Scanner(InputStream system) {
            br = new BufferedReader(new InputStreamReader(system));
        }

        public Scanner(String file) throws Exception {
            br = new BufferedReader(new FileReader(file));
        }

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

        public String nextLine() throws IOException {
            return br.readLine();
        }

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

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

        public char nextChar() throws IOException {
            return next().charAt(0);
        }

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

        public boolean ready() throws IOException {
            return br.ready();
        }

        public void waitForInput() throws InterruptedException {
            Thread.sleep(3000);
        }
    }
}

import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;

public class E {

    public static int[] sums_on_subarray(int[] a, int size, int from, int m) {
        int[] sums = new int[1 << size];
        for (int i = 0; i < 1 << size; i++) {
            int sum = 0;
            for (int j = 0; j < size; j++) {
                if ((i & 1 << j) > 0) {
                    sum = (sum + a[j + from]) % m;
                }
            }

            sums[i] = sum;
        }

        return sums;
    }

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

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

        for (int i = 0; i < n; i++) {
            a[i] = in.nextInt();
        }

        int[] x = sums_on_subarray(a, n / 2, 0, m);
        int[] y = sums_on_subarray(a, n - n / 2, n / 2, m);

        Arrays.sort(y);

        int ans = 0;
        for (int i = 0; i < x.length; i++) {
            int p1 =  Arrays.binarySearch(y, m - 1);
            int p2 = Arrays.binarySearch(y, m - x[i] - 1);

            if (p1 < 0) {
                p1 = -(p1 + 1) - 1; // + 1;
            }
            if (p2 < 0) {
                p2 = -(p2 + 1) - 1; // + 1;
            }

            ans = Math.max(ans, (x[i] + y[p1]) % m);
            ans = Math.max(ans, (x[i] + y[p2]) % m);
        }

        out.println(ans);

        in.close();
        out.close();
    }
}

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.TreeSet;

public class MaximumSubsequence {

	static void check(int[] arr, int m) {
		int res = 0;
		int mask = -1;
		for (int i = 0; i < (1 << arr.length); i++) {
			int sum = 0;
			for (int j = 0; j < arr.length; j++) {
				if ((i & (1 << j)) > 0) {
					sum += arr[j];
					sum %= m;
				}
			}
			if (sum > res) {
				res = sum;
				mask = i;
			}
		}
		System.out.println(Integer.toBinaryString(mask));
	}

	public static void main(String[] args) {
		InputReader r = new InputReader(System.in);
		int n = r.nextInt();
		int m = r.nextInt();
		int[] arr = new int[n];
		for (int i = 0; i < arr.length; i++) {
			arr[i] = r.nextInt() % m;
		}
		int half = n / 2;
		int other = n - half;
		TreeSet<Integer> set = new TreeSet<Integer>();
		int res = 0;
		for (int i = 0; i < (1 << other); i++) {
			int sum = 0;
			for (int j = 0; j < other; j++) {
				if ((i & (1 << j)) > 0) {
					sum += arr[half + j];
					sum %= m;
				}
			}
			res = Math.max(res, sum);
			set.add(sum);
		}
		for (int i = 0; i < (1 << half); i++) {
			int sum = 0;
			for (int j = 0; j < half; j++) {
				if ((i & (1 << j)) > 0) {
					sum += arr[j];
					sum %= m;
				}
			}
			res = Math.max(res, sum);
			int need = m - sum;
			Integer get = set.lower(need);
			if (get != null) {
				res = Math.max(res, (get + sum) % m);
			}
		}
		System.out.println(res);
	}

	static class InputReader {
		private BufferedReader reader;
		private StringTokenizer tokenizer;

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

		public InputReader(FileReader stream) {
			reader = new BufferedReader(stream);
			tokenizer = null;
		}

		public String nextLine() {
			try {
				return reader.readLine();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return null;
			}
		}

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

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

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

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

import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;

public class Main {

	public static ArrayList<Integer>g1 = new ArrayList<>();

	public static int bSearch(int val){
		int st = 0, end = g1.size() - 1;

		while(st < end){
			int mid = st + (end - st + 1) / 2;

			if(g1.get(mid) < val){
				st = mid;

			}else{

				end = mid - 1;
			}
		}
		return g1.get(st);
	}

	public static void main(String [] args){
		Scanner scanner = new Scanner(System.in);
		int n = scanner.nextInt();
		int m = scanner.nextInt();
		int size1 = n/2;
		ArrayList<Integer>nums = new ArrayList<>();

		for(int i = 0; i < n; i++){
			nums.add(scanner.nextInt());
		}

		for(int msk = 0; msk < (1 << size1); msk++){

			int sum = 0;
			for(int i = 0; i < size1; i++){
				if((msk & (1 << i)) >= 1){
					sum+= nums.get(i);
					sum%= m;
				}
			}

			g1.add(sum);
		}
		Collections.sort(g1);

		int res = 0;
		int size2  = n - size1;
		for(int msk = 0; msk < (1 << size2); msk++){

			int sum = 0;
			for(int i = 0; i < size2; i++){
				if((msk & (1 << i)) >= 1){
					sum+= nums.get(size1 + i);
					sum%= m;
				}
			}

			int val = m - sum;
			res =  Math.max(res, sum + bSearch(val));

		}

		System.out.println(res);
	}
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.TreeSet;
import java.util.ArrayList;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author Sanket Makani
 */
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);
        TaskE solver = new TaskE();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskE {
        public void solve(int testNumber, InputReader sc, PrintWriter w) {

            int n = sc.nextInt();
            long m = sc.nextLong();

            TreeSet<Long> set1 = new TreeSet<>();
            TreeSet<Long> set2 = new TreeSet<>();

            ArrayList<Long> list = new ArrayList<>();

            long arr[] = new long[n];

            for (int i = 0; i < n; i++)
                arr[i] = sc.nextInt();

            for (int i = 0; i < n / 2; i++)
                list.add(arr[i]);

            getPermutation(list, set1, m);

            list.clear();

            for (int i = n / 2; i < n; i++)
                list.add(arr[i]);

            getPermutation(list, set2, m);

            long max = -1;

            max = Math.max(set1.last(), set2.last());
            //w.println(set1);
            // w.println(set2);
            for (long in : set1) {
                max = Math.max(max, in);
                long searchFor = m - in - 1;
                Long key = set2.floor(searchFor);
                if (key != null)
                    max = Math.max((in + key) % m, max);
            }

            w.println(max);
        }

        private void getPermutation(ArrayList<Long> list, TreeSet<Long> set, long mod) {
            int total = list.size();

            int pow = (int) Math.pow(2, total);
            set.add(0L);
            for (int i = 1; i < pow; i++) {
                long curr = 0;

                for (int j = 0; j < total; j++) {
                    if ((i & (1 << j)) != 0) {
                        curr += list.get(j);
                        curr %= mod;
                    }
                }

                set.add(curr);
            }

        }

    }

    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private InputReader.SpaceCharFilter filter;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars == -1)
                throw new InputMismatchException();

            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }

                if (numChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }

        public int nextInt() {
            int c = read();

            while (isSpaceChar(c))
                c = read();

            int sgn = 1;

            if (c == '-') {
                sgn = -1;
                c = read();
            }

            int res = 0;
            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            }
            while (!isSpaceChar(c));

            return res * sgn;
        }

        public long nextLong() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            long res = 0;

            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            }
            while (!isSpaceChar(c));
            return res * sgn;
        }

        public boolean isSpaceChar(int c) {
            if (filter != null)
                return filter.isSpaceChar(c);
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);

        }

    }
}

/**
 * Created by Aminul on 11/28/2018.
 */

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

public class CF888E {
    public static void main(String[] args)throws Exception {
        FastReader in = new FastReader(System.in);
        PrintWriter pw = new PrintWriter(System.out);
        int n = in.nextInt(), m = in.nextInt();
        int arr[] = new int[n];
        for (int i = 0; i < n; i++) {
            arr[i] = in.nextInt();
        }
        int a[] = solve(Arrays.copyOfRange(arr, 0, n/2), m);
        int b[] = solve(Arrays.copyOfRange(arr, (n/2), n), m);
        int max = 0;
        for(int i : a) {
            int need = m - 1 - i;
            int floor = floor(b, need);
            if(floor != -1) max = max(max, i + b[floor]);
        }
        for(int i : b) {
            int need = m - 1 - i;
            int floor = floor(a, need);
            if(floor != -1) max = max(max, i + a[floor]);
        }
        pw.println(max);
        pw.close();
    }

    static int[] solve(int a[], int mod) {
        int n = a.length;
        int res[] = new int[1 << n];
        for (int i = 0; i < (1 << n); i++) {
            int sum = 0;
            for(int j = 0; j < n; j++) {
                if(check(i, j)) {
                    if(a[j] >= mod) a[j] %= mod;
                    sum += a[j];
                    if(sum >= mod) sum -= mod;
                }
            }
            res[i] = sum;
        }
        Arrays.sort(res);
        return res;
    }

    static int floor(int arr[], int key) {
        int lo = 0, hi = arr.length - 1, mid;
        while (lo < hi) {
            mid = (lo + hi) / 2;
            if (arr[mid] > key) hi = mid;
            else lo = mid + 1;
        }
        return (lo >= arr.length || arr[lo] > key) ? lo-1: lo;
        //returns right Most index where arr[lo] <= key
        //returns -1 if all values are greater than key
    }

    static boolean check(int N,int pos){return (N & (1<<pos)) != 0;}
    static int set(int N,int pos){return N=N | (1<<pos);}
    static int reset(int N,int pos){return N= N & ~(1<<pos);}

    static void debug(Object...obj) {
        System.err.println(Arrays.deepToString(obj));
    }

    static class FastReader {
        InputStream is;
        private byte[] inbuf = new byte[1024];
        private int lenbuf = 0, ptrbuf = 0;

        public FastReader(InputStream is) {
            this.is = is;
        }

        public int readByte() {
            if (lenbuf == -1) throw new InputMismatchException();
            if (ptrbuf >= lenbuf) {
                ptrbuf = 0;
                try {
                    lenbuf = is.read(inbuf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (lenbuf <= 0) return -1;
            }
            return inbuf[ptrbuf++];
        }

        public boolean isSpaceChar(int c) {
            return !(c >= 33 && c <= 126);
        }
        private boolean isEndOfLine(int c) {
            return c == '\n' || c == '\r' || c == -1;
        }

        public int skip() {
            int b;
            while ((b = readByte()) != -1 && isSpaceChar(b)) ;
            return b;
        }

        public String next() {
            int b = skip();
            StringBuilder sb = new StringBuilder();
            while (!(isSpaceChar(b))) {
                sb.appendCodePoint(b);
                b = readByte();
            }
            return sb.toString();
        }

        public String nextLine() {
            int c = skip();
            StringBuilder sb = new StringBuilder();
            while (!isEndOfLine(c)){
                sb.appendCodePoint(c);
                c = readByte();
            }
            return sb.toString();
        }

        public int nextInt() {
            int num = 0, b;
            boolean minus = false;
            while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
            if (b == '-') {
                minus = true;
                b = readByte();
            }
            while (true) {
                if (b >= '0' && b <= '9') {
                    num = (num << 3) + (num << 1) + (b - '0');
                } else {
                    return minus ? -num : num;
                }
                b = readByte();
            }
        }

        public long nextLong() {
            long num = 0;
            int b;
            boolean minus = false;
            while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
            if (b == '-') {
                minus = true;
                b = readByte();
            }

            while (true) {
                if (b >= '0' && b <= '9') {
                    num = (num << 3) + (num << 1) + (b - '0');
                } else {
                    return minus ? -num : num;
                }
                b = readByte();
            }
        }

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

        public char[] next(int n) {
            char[] buf = new char[n];
            int b = skip(), p = 0;
            while (p < n && !(isSpaceChar(b))) {
                buf[p++] = (char) b;
                b = readByte();
            }
            return n == p ? buf : Arrays.copyOf(buf, p);
        }

        public char readChar() {
            return (char) skip();
        }
    }
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.StringTokenizer;
import java.util.TreeSet;

public class MaximumSubsequence {

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

	ArrayList<Integer> left;
	TreeSet<Integer> right;
	int M;

	public void run() throws IOException
	{
		BufferedReader file = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer(file.readLine());
		int N = Integer.parseInt(st.nextToken());
		M = Integer.parseInt(st.nextToken());
		int[] firstHalf = new int[N/2];
		int[] secondHalf = new int[N - firstHalf.length];
		st = new StringTokenizer(file.readLine());
		for(int i = 0;i<firstHalf.length;i++)
		{
			firstHalf[i] = Integer.parseInt(st.nextToken());
		}
		for(int i = 0;i<secondHalf.length;i++)
		{
			secondHalf[i] = Integer.parseInt(st.nextToken());
		}
		left = new ArrayList<Integer>();
		right = new TreeSet<Integer>();
		permute(firstHalf, 0, 0, left);
		permute(secondHalf,0,0,right);
		int max = 0;
		for(int i:left)
		{
			max = Math.max(max, i+right.lower(M-i));
		}
		System.out.println(max);
	}

	public void permute(int[] ints, int sum, int index, Collection<Integer> add)
	{
		if(index == ints.length)
			add.add(sum);
		else{
			permute(ints, sum, index+1, add);
			permute(ints, (sum+ints[index])%M, index+1, add);
		}
	}
}

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

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

    static class TaskE {
        public void solve(int testNumber, FastScanner 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() % m;
            }

            int ret = 0;
            TreeSet<Integer> tree = new TreeSet<>();
            int N = (n + 1) / 2;
            for (int mask = 0; mask < (1 << N); ++mask) {
                int sum = 0;
                for (int i = 0; i < N; ++i) {
                    if ((mask & (1 << i)) > 0) {
                        sum += a[i];
                        if (sum >= m) {
                            sum -= m;
                        }
                    }
                }
                tree.add(sum);
            }
            int M = n - N;
            for (int mask = 0; mask < (1 << M); ++mask) {
                int sum = 0;
                for (int i = 0; i < M; ++i) {
                    if ((mask & (1 << i)) > 0) {
                        sum += a[N + i];
                        if (sum >= m) {
                            sum -= m;
                        }
                    }
                }
                int rem = m - 1 - sum;
                Integer floor = tree.floor(rem);
                if (floor != null) {
                    ret = Math.max(ret, floor + sum);
                }
            }

            out.println(ret);
        }

    }

    static class FastScanner {
        BufferedReader in;
        StringTokenizer token;
        String delim;

        public FastScanner(InputStream inputStream) {
            this.in = new BufferedReader(new InputStreamReader(inputStream));
            this.delim = " \n\t";
            this.token = new StringTokenizer("", delim);
        }

        public FastScanner(InputStream inputStream, String delim) {
            this.in = new BufferedReader(new InputStreamReader(inputStream));
            this.delim = delim;
            this.token = new StringTokenizer("", delim);
        }

        public boolean hasNext() {
            while (!token.hasMoreTokens()) {
                try {
                    String s = in.readLine();
                    if (s == null) return false;
                    token = new StringTokenizer(s, delim);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
            }
            return true;
        }

        public String next() {
            hasNext();
            return token.nextToken();
        }

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

    }
}

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Random;
import java.util.StringTokenizer;

import javax.swing.text.StyledEditorKit.ForegroundAction;

public class E {

	static StringTokenizer st;
	static BufferedReader br;
	static PrintWriter pw;
	public static void main(String[] args) throws IOException {
		br = new BufferedReader(new InputStreamReader(System.in));
		pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
		int n = nextInt();
		int m = nextInt();
		int[]a = new int[n];
		for (int i = 0; i < n; i++) {
			a[i] = nextInt() % m;
		}
		if (n==1) {
			System.out.println(a[0]);
			return;
		}
		int n1 = n / 2 + 1;

		ArrayList<Integer> first = calcMods(a, 0, n1, m);
		ArrayList<Integer> second = calcMods(a, n1, n, m);
		Collections.sort(first);

//		ArrayList<Integer> last = calcMods(a, 0, n, m);
//		Collections.sort(last);
//		System.out.println(last.get(last.size()-1));

		int ans = 0;
		for (int i : first) {
			ans = Math.max(ans, i);
		}
		for (int x : second) {
			ans = Math.max(ans, x);
			int i = Collections.binarySearch(first, m-1-x);
			if (i < 0)
				i = Math.abs(i)-2;
			if (i >= 0)
				ans = Math.max(ans, (x + first.get(i)) % m);
			ans = Math.max(ans, (x + first.get(first.size()-1)) % m);
		}
		System.out.println(ans);
		pw.close();
	}
	private static ArrayList<Integer> calcMods(int[] a, int from, int to, int m) {
		int[]b = new int[a.length];
		int n = to-from;
		for (int i = from; i < to; i++) {
			b[i-from] = a[i];
		}
		ArrayList<Integer> res = new ArrayList<>();
		for (int mask = 0; mask < (1 << n); mask++) {
			int sum = 0;
			for (int i = 0; i < n; i++) {
				if ((mask & (1 << i)) != 0) {
					sum += b[i];
					if (sum >= m)
						sum -= m;
				}
			}
			res.add(sum);
		}
		return res;
	}
	private static int nextInt() throws IOException {
		return Integer.parseInt(next());
	}
	private static long nextLong() throws IOException {
		return Long.parseLong(next());
	}
	private static double nextDouble() throws IOException {
		return Double.parseDouble(next());
	}
	private static String next() throws IOException {
		while (st==null || !st.hasMoreTokens())
			st = new StringTokenizer(br.readLine());
		return st.nextToken();
	}
}
/*
30
78945
*/

import java.io.*; import java.util.*;
public class CF0888E {

    /**
     * Idea: split the sequence into two parts of size <=18
     *
     * Perform a bitmasking search for the two parts
     * Sort two parts
     * And merge
     *
     * To merge, we first consider the sum of largest elements.
     *
     * Now perform a two pointer on sum <=MOD to get largest sum <=MOD
     * DONE
     */
    public static void main(String[] args) throws IOException {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st=new StringTokenizer(br.readLine());
        int N=Integer.parseInt(st.nextToken());
        int MOD=Integer.parseInt(st.nextToken());
        st=new StringTokenizer(br.readLine());
        int[] p1=new int[N/2];
        for (int i = 0; i < N/2; i++) {
            p1[i]=Integer.parseInt(st.nextToken())%MOD;
        }
        int[] p2=new int[N-N/2];
        for (int i = 0; i < N-N/2; i++) {
            p2[i]=Integer.parseInt(st.nextToken())%MOD;
        }

        ArrayList<Integer> res1=new ArrayList<>();
        int cur=0;
        for (int i = 0; i < (1<<N/2); i++) {
            cur=0;
            for (int j = 0; j < N/2; j++) {
                if((i&(1<<j))>0){
                    cur+=p1[j]; cur%=MOD;
                }
            }
            res1.add(cur);
        }
        ArrayList<Integer> res2=new ArrayList<>();
        for (int i = 0; i < (1<<(N-N/2)); i++) {
            cur=0;
            for (int j = 0; j < N-N/2; j++) {
                if((i&(1<<j))>0){
                    cur+=p2[j]; cur%=MOD;
                }
            }
            res2.add(cur);
        }
        Collections.sort(res1); Collections.sort(res2);
        //System.out.println(res1+" "+res2);
        int max=(res1.get(res1.size()-1)+res2.get(res2.size()-1))%MOD;
        //Now consider sums <MOD, we use 2 pointers
        int rp=res2.size()-1;
        for (int l = 0; l < res1.size(); l++) {
            while(rp>=0 && res1.get(l)+res2.get(rp)>=MOD){
                rp--;
            }
            if(rp<0){
                break;
            }
            max=Math.max(max,res1.get(l)+res2.get(rp));
        }
        System.out.println(max);
    }

}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

public class Main {

    public static void main(String[] args) {
        MyScanner in = new MyScanner();
        int n = in.nextInt();
        int m = in.nextInt();
        int divider = 2;
        Set<Integer>[] parts = new HashSet[divider];
        for (int i = 0; i < divider; i++) {
            parts[i] = new HashSet<>();
        }

        int max = 0;
        for (int i = 0; i < n; i++) {
            Set set = parts[i % divider];
            int v = in.nextInt() % m;
            Iterator<Integer> iterator = set.iterator();
            List<Integer> list = new ArrayList<>();
            list.add(v);
            while (iterator.hasNext()) {
                int v2 = (iterator.next() + v) % m;
                if (set.contains(v2)) continue;
                list.add(v2);
            }
            set.addAll(list);
        }

        List<Integer> list1 = new ArrayList<>(parts[0]);
        list1.add(0);
        Collections.sort(list1);
        parts[1].add(0);

        for (int v : parts[1]) {
            int index = Collections.binarySearch(list1, m - v - 1);

            if(index >= 0){
                max = m - 1;
                break;
            } else {
                max = Math.max(max, list1.get(-index - 2) + v);
            }
        }

        System.out.println(max);
    }

    static class MyScanner {
        BufferedReader br;
        StringTokenizer st;

        public MyScanner() {
            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;
        }
    }
}

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

public class CF888E {
	static int[] brute(int[] aa, int n, int m) {
		ArrayList<Integer> list = new ArrayList<>();
		for (int b = 0; b < 1 << n; b++) {
			int r = 0;
			for (int i = 0; i < n; i++)
				if ((b & 1 << i) != 0)
					r = (r + aa[i]) % m;
			list.add(r);
		}
		Collections.sort(list);
		int k = list.size();
		int[] rr = new int[k];
		k = 0;
		for (int r : list)
			rr[k++] = r;
		return rr;
	}
	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer(br.readLine());
		int n = Integer.parseInt(st.nextToken());
		int m = Integer.parseInt(st.nextToken());
		st = new StringTokenizer(br.readLine());
		if (n == 1) {
			int a = Integer.parseInt(st.nextToken());
			System.out.println(a % m);
			return;
		}
		int na = n / 2, nb = n - na;
		int[] aa = new int[na];
		int[] bb = new int[nb];
		for (int i = 0; i < na; i++)
			aa[i] = Integer.parseInt(st.nextToken());
		for (int i = 0; i < nb; i++)
			bb[i] = Integer.parseInt(st.nextToken());
		int[] rr = brute(aa, na, m);
		int[] ss = brute(bb, nb, m);
		int nr = rr.length;
		int ns = ss.length;
		int max = Math.max(rr[nr - 1], ss[ns - 1]);
		for (int i = 0, j = ns - 1; j >= 0; j--) {
			while (i < nr && rr[i] + ss[j] < m)
				i++;
			int r = (i == 0 ? 0 : rr[i - 1]) + ss[j];
			if (max < r)
				max = r;
		}
		System.out.println(max);
	}
}

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

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

    static class E {
        private long[] getSums(int[] a, int from, int to, long mod) {
            int n = to - from;
            long[] res = new long[1 << n];
            for (int mask = 0; mask < 1 << n; mask++) {
                long sum = 0;
                for (int i = 0; i < n; i++) {
                    if ((mask & (1 << i)) > 0) {
                        sum += a[from + i];
                    }
                }
                res[mask] = sum % mod;
            }
            return res;
        }

        public void solve(int testNumber, FastScanner in, PrintWriter out) {
            int n = in.ni(), m = in.ni();
            long mod = m;
            int[] a = in.na(n);
            for (int i = 0; i < n; i++) {
                a[i] %= m;
            }
            if (n == 1) {
                out.println(a[0]);
                return;
            }
            long[] p1 = getSums(a, 0, n / 2, mod);
            long[] p2 = getSums(a, n / 2, n, mod);
            Arrays.sort(p1);
            Arrays.sort(p2);
//        System.out.println("Arrays.toString(p1) = " + Arrays.toString(p1));
//        System.out.println("Arrays.toString(p2) = " + Arrays.toString(p2));
            long ans = 0;
            int right = p2.length - 1;
            for (int i = 0; i < p1.length; i++) {
                while (right >= 0 && p1[i] + p2[right] >= mod) {
                    right--;
                }
                ans = Math.max(ans, (p1[i] + p2[right]));
            }
            out.println(ans);

        }

    }

    static class FastScanner {
        private BufferedReader in;
        private StringTokenizer st;

        public FastScanner(InputStream stream) {
            in = new BufferedReader(new InputStreamReader(stream));
        }

        public String ns() {
            while (st == null || !st.hasMoreTokens()) {
                try {
                    String rl = in.readLine();
                    if (rl == null) {
                        return null;
                    }
                    st = new StringTokenizer(rl);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return st.nextToken();
        }

        public int ni() {
            return Integer.parseInt(ns());
        }

        public int[] na(int n) {
            int[] a = new int[n];
            for (int i = 0; i < n; i++) a[i] = ni();
            return a;
        }

    }
}

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

public class EC32P5
{
    private static long[] arr;

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

        int n = in.nextInt();
        int m = in.nextInt();

        int[] arr1 = new int[n/2];
        int[] arr2 = new int[n - n/2];

        for(int i=0; i<n/2; i++)
        {
            arr1[i] = in.nextInt();
        }

        for(int i=0; i<n - n/2; i++)
        {
            arr2[i] = in.nextInt();
        }

        int[] sum1 = sums_on_subarray(arr1, n/2, 0, m);
        int[] sum2 = sums_on_subarray(arr2, n- n/2, 0, m);
        Arrays.sort(sum1);

        int counter = 0;;

        for(int i=0; i<sum2.length; i++)
        {
            int sum = 0;
            int key = Arrays.binarySearch(sum1, m-1-sum2[i]);
            int key2 = Arrays.binarySearch(sum1, m-1);

            if(key<0)
            {
                key = -(key+2);
            }

            if(key2<0)
            {
                key2 = -(key2 + 2);
            }

            sum = sum2[i] + sum1[key];
            sum = Math.max(sum, (sum2[i] + sum1[key2]) % m);

            if(sum > counter)
            {
                counter = sum;
            }

        }

        System.out.println(counter);
    }

    public static int[] sums_on_subarray(int[] a, int size, int from, int m) {
        int[] sums = new int[1 << size];
        for (int i = 0; i < 1 << size; i++) {
            int sum = 0;
            for (int j = 0; j < size; j++) {
                if ((i & 1 << j) > 0) {
                    sum = (sum + a[j + from]) % m;
                }
            }

            sums[i] = sum;
        }

        return sums;
    }

}

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

public class tr0 {
	static PrintWriter out;
	static StringBuilder sb;
	static int mod = 1000000007;
	static long inf = (long) 1e16;
	static int[][] ad;
	static int n, m;
	static long[][][] memo;
	static HashSet<Integer> h;
	static long[] a;
	static HashSet<Integer> leaves;
	static TreeMap<pair, Long> dp;
	static ArrayList<Long> ar;

	public static void main(String[] args) throws Exception {
		Scanner sc = new Scanner(System.in);
		out = new PrintWriter(System.out);
		n = sc.nextInt();
		m = sc.nextInt();
		a = sc.nextArrLong(n);
		ar = new ArrayList<>();
		v = 0;
		cal(0);
		Collections.sort(ar);
		v = 0;
		ans = 0;
		cal2(n / 2);
		System.out.println(ans);
		out.close();
	}

	static long v, ans;

	static void cal(int i) {
		if (i == n / 2) {
			ans = Math.max(ans, v % m);
			ar.add(v % m);
			return;
		}
		cal(i + 1);
		v += a[i];
		cal(i + 1);
		v -= a[i];
	}

	static void cal2(int i) {
		if (i == n) {
			long x = v % m;
			ans = Math.max(ans, (x + ar.get(ar.size() - 1)) % m);
			int lo = 0;
			int hi = ar.size() - 1;
			long tem = 0;
			while (lo <= hi) {
				int mid = (lo + hi) >> 1;
				if (x + ar.get(mid) >= m) {
					hi = mid - 1;
				} else {
					tem = ar.get(mid);
					lo = mid + 1;
				}
			}
			ans = Math.max(ans, (x + tem)%m);
			return;
		}
		cal2(i + 1);
		v += a[i];
		cal2(i + 1);
		v -= a[i];
	}

	static class pair implements Comparable<pair> {
		int to;
		long number;

		pair(int t, long n) {
			number = n;
			to = t;
		}

		public String toString() {
			return to + " " + number;
		}

		@Override
		public int compareTo(pair o) {
			if (to == o.to)
				return Long.compare(number, o.number);
			return to - o.to;
		}

	}

	static class Scanner {
		StringTokenizer st;
		BufferedReader br;

		public Scanner(InputStream system) {
			br = new BufferedReader(new InputStreamReader(system));
		}

		public Scanner(String file) throws Exception {
			br = new BufferedReader(new FileReader(file));
		}

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

		public String nextLine() throws IOException {
			return br.readLine();
		}

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

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

		public char nextChar() throws IOException {
			return next().charAt(0);
		}

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

		public int[] nextArrInt(int n) throws IOException {
			int[] a = new int[n];
			for (int i = 0; i < n; i++)
				a[i] = nextInt();
			return a;
		}

		public long[] nextArrLong(int n) throws IOException {
			long[] a = new long[n];
			for (int i = 0; i < n; i++)
				a[i] = nextLong();
			return a;
		}

		public boolean ready() throws IOException {
			return br.ready();
		}

		public void waitForInput() throws InterruptedException {
			Thread.sleep(3000);
		}
	}
}

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

public class A implements Runnable{
	public static void main (String[] args) {new Thread(null, new A(), "_cf", 1 << 28).start();}

	public void run() {
		FastScanner fs = new FastScanner();
		PrintWriter out = new PrintWriter(System.out);

		int n = fs.nextInt();
		int m = fs.nextInt();
		int[] a = fs.nextIntArray(n);

		if(n == 1) {
			System.out.println(a[0] % m);
			return;
		}

		long res = 0;
		int go = n >> 1;
		TreeSet<Long> set = new TreeSet<>();
		for(int i = 0; i < (1 << go); i++) {
			long sum = 0;
			for(int j = 0; j < go; j++) {
				int on = i & (1 << j);
				if(on == 0) continue;
				sum += a[j];
				while(sum >= m) sum -= m;
			}
			res = Math.max(res, sum);
			set.add(sum);
		}

		int old = go;
		go = n - old;
		for(int i = 0; i < (1 << go); i++) {
			long sum = 0;
			for(int j = 0; j < go; j++) {
				int on = i & (1 << j);
				if(on == 0) continue;
				sum += a[j + old];
				while(sum >= m) sum -= m;
			}
			if(sum < m-1) {
				long need = m - sum - 1;
				if(set.floor(need) != null) {
					res = Math.max(res, (set.floor(need) + sum) % m);
				}
			}
			res = Math.max(res, sum);
		}

		out.println(res);

		out.close();
	}

	int n, k;

	class FastScanner {
		BufferedReader br;
		StringTokenizer st;
		public FastScanner() {
			try	{
				br = new BufferedReader(new InputStreamReader(System.in));
				//                br = new BufferedReader(new FileReader("testdata.out"));
				st = new StringTokenizer("");
			} catch (Exception e){e.printStackTrace();}
		}
		public String next() {
			if (st.hasMoreTokens())	return st.nextToken();
			try {st = new StringTokenizer(br.readLine());}
			catch (Exception e) {e.printStackTrace();}
			return st.nextToken();
		}
		public int nextInt() {return Integer.parseInt(next());}
		public long nextLong() {return Long.parseLong(next());}
		public double nextDouble() {return Double.parseDouble(next());}

		public String nextLine() {
			String line = "";
			try {line = br.readLine();}
			catch (Exception e) {e.printStackTrace();}
			return line;
		}
		public Integer[] nextIntegerArray(int n) {
			Integer[] a = new Integer[n];
			for(int i = 0; i < n; i++) a[i] = nextInt();
			return a;
		}
		public int[] nextIntArray(int n) {
			int[] a = new int[n];
			for(int i = 0; i < n; i++) a[i] = nextInt();
			return a;
		}
		public char[] nextCharArray() {return nextLine().toCharArray();}
	}

}

import java.io.*;
import java.util.*;
public class E {
	public static void main(String[] args)throws Throwable {
		MyScanner sc=new MyScanner();
		PrintWriter pw=new PrintWriter(System.out);

		int n=sc.nextInt();
		m=sc.nextInt();
		a=new ArrayList<Integer>();
		b=new ArrayList<Integer>();
		A=new ArrayList<Integer>();
		B=new ArrayList<Integer>();
		for(int i=0;i<n;i++){
			int x=sc.nextInt()%m;
			if(i<n/2)
				a.add(x);
			else
				b.add(x);
		}
		goA(0,0);
		goB(0,0);
		Collections.sort(A);
		Collections.sort(B);
		int ans=Math.max(A.get(A.size()-1), B.get(B.size()-1));
		for(int x : A){
			int start=0,end=B.size()-1,res=-1;
			while(start<=end){
				int mid=((start+end)>>1);
				if(B.get(mid)<m-x){
					res=B.get(mid);
					start=mid+1;
				}else
					end=mid-1;
			}
			if(res!=-1)
				ans=Math.max(ans, (x+res)%m);
			ans=Math.max(ans, (x+B.get(B.size()-1))%m);
		}

		pw.println(ans);
		pw.flush();
		pw.close();
	}
	static int m;
	static ArrayList<Integer> a,b;
	static ArrayList<Integer> A,B;

	static void goA(int i,int soFar){
		if(i==a.size()){
			A.add(soFar);
			return;
		}
		goA(i+1, soFar);
		goA(i+1, (soFar+a.get(i))%m);
	}

	static void goB(int i,int soFar){
		if(i==b.size()){
			B.add(soFar);
			return;
		}
		goB(i+1, soFar);
		goB(i+1, (soFar+b.get(i))%m);
	}

	static class MyScanner {
		BufferedReader br;
		StringTokenizer st;
		public MyScanner() {
			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;}
	}
}

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

public class Main {

    void solve() throws IOException {
        int n = readInt();
        int m = readInt();
        int[] a = readIntArray(n);
        for (int i =0;i<n;i++) a[i]%=m;
        HashSet<Integer> set1 = new HashSet<Integer>();
        HashSet<Integer> set2 = new HashSet<Integer>();
        HashSet<Integer> delta = new HashSet<Integer>();
        for (int i = 0; i < n / 2; i++) {
            delta.clear();
            for (int j : set1) delta.add((j + a[i]) % m);
            for (int j : delta) set1.add(j);
            set1.add(a[i]);
        }
        for (int i = n / 2; i < n; i++) {
            delta.clear();
            for (int j : set2) delta.add((j + a[i]) % m);
            for (int j : delta) set2.add(j);
            set2.add(a[i]);
        }

        TreeSet<Integer> s1 = new TreeSet<Integer>();
        TreeSet<Integer> s2 = new TreeSet<Integer>();
        s1.add(0);
        s2.add(0);
        for (int i : set1) s1.add(i);
        for (int i : set2) s2.add(i);
        int answer = 0;
        for (int i : s1) {
            if (s2.lower(m - i) != null) {
                answer = maxInt(answer, i + s2.lower(m - i));
            }
        }
        for (int i : s2) {
            if (s1.lower(m - i) != null) {
                answer = maxInt(answer, i + s1.lower(m - i));
            }
        }
        out.println(answer);
    }

    class SegmentTree {
        int[] t;

        SegmentTree(int[] a, int n) {
            t = new int[4 * n];
            build(a, 1, 1, n);
        }

        void build(int[] a, int v, int tl, int tr) {
            if (tl == tr) {
                t[v] = a[tl];
                return;
            }

            int tm = (tl + tr) / 2;
            build(a, 2 * v, tl, tm);
            build(a, 2 * v + 1, tm + 1, tr);
            t[v] = Math.min(t[2 * v], t[2 * v + 1]);
        }

        void update(int v, int tl, int tr, int pos, int value) {
            if (tl == tr) {
                t[v] = value;
                return;
            }
            int tm = (tl + tr) / 2;
            if (pos <= tm) {
                update(2 * v, tl, tm, pos, value);
            } else {
                update(2 * v + 1, tm + 1, tr, pos, value);
            }

            t[v] = Math.min(t[2 * v], t[2 * v + 1]);
        }

        int getMin(int v, int tl, int tr, int l, int r) {
            if (l > r) {
                return INF;
            }
            if (tl == l && tr == r) {
                return t[v];
            }

            int tm = (tl + tr) / 2;

            int min1 = getMin(2 * v, tl, tm, l, Math.min(tm, r));
            int min2 = getMin(2 * v + 1, tm + 1, tr, Math.max(l, tm + 1), r);

            return Math.min(min1, min2);
        }
    }

    int checkBit(int mask, int bit) {
        return (mask >> bit) & 1;
    }

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

        new Main().run();
    }

    boolean isLower(char a) {
        return ((int) a) >= 97 ? true : false;
    }

    int INF = Integer.MAX_VALUE / 10;

    int[][] STEPS = {{0, 1}, {1, 0}, {-1, 0}, {0, -1}};

    BufferedReader in;
    PrintWriter out;
    StringTokenizer tok;
    Random rnd = new Random();
    static final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;

    Main() throws FileNotFoundException {

        try {
            in = new BufferedReader(new FileReader("input.txt"));
            out = new PrintWriter("output.txt");
        } catch (Exception e) {
            in = new BufferedReader(new InputStreamReader(System.in));
            out = new PrintWriter(System.out);
        }

        tok = new StringTokenizer("");
    }

    long checkBit(long mask, int bit) {
        return (mask >> bit) & 1;
    }

    void run() throws IOException {
        solve();
        out.close();
    }

    char varChar;
    int varInt, varInt1, varInt2;
    long varLong;

    void swapInt(int a, int b) {
        varInt = a;
        a = b;
        b = varInt;
    }

    void swapChar(char a, char b) {
        varChar = a;
        a = b;
        b = varChar;
    }

    void swapLong(long a, long b) {
        varLong = a;
        a = b;
        b = varLong;
    }

    void reverseCharArray(char[] arr) {
        for (int i = 0; i < arr.length; i++) swapChar(arr[i], arr[arr.length - i - 1]);
    }

    int sqrt(double m) {
        varInt1 = 0;
        varInt2 = Integer.MAX_VALUE;
        int i = 1000;
        while (varInt2 >= varInt2) {
            i = (varInt2 + varInt1) / 2;
            if ((long) i * i > m) {
                varInt2 = i - 1;
            } else {
                varInt1 = i + 1;
                varInt = varInt1 - 1;
            }
        }
        return varInt;
    }

    int countPow(int m, int n) {
        varInt = 0;
        while (m % n == 0 && m > 0) {
            varInt++;
            m /= n;
        }
        return varInt;
    }

    long binPow(long a, long b) {
        if (b == 0) {
            return 1;
        }
        if (b % 2 == 1) {
            return a * binPow(a, b - 1);
        } else {
            varLong = binPow(a, b / 2);
            return varLong * varLong;
        }

    }

    int gcd(int a, int b) {
        return b == 0 ? a : gcd(b, a % b);
    }

    long pow(long x, long k) {
        varLong = 1;
        for (int i = 0; i < k; ++i) {
            varLong *= x;
        }
        return varLong;
    }

    class Fenwik {
        private long[] t;
        private int length;

        Fenwik(int[] a) {
            this.length = a.length + 100;
            this.t = new long[length];
            for (int i = 0; i < a.length; ++i) {
                this.inc(i, a[i]);
            }
        }

        void inc(int i, int delta) {
            for (; i < this.length; i = i | (i + 1)) {
                this.t[i] += delta;
            }
        }

        long getSum(int r) {
            long sum = 0;

            for (; r >= 0; r = (r & (r + 1)) - 1) {
                sum += this.t[r];
            }

            return sum;
        }
    }

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

    String delimiter = " ";

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

    String readString() throws IOException {
        while (!tok.hasMoreTokens()) {
            String nextLine = readLine();
            if (null == nextLine)
                return null;

            tok = new StringTokenizer(nextLine);
        }

        return tok.nextToken(delimiter);
    }

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

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

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

    int[] readIntArray(int b) {
        int a[] = new int[b];
        for (int i = 0; i < b; i++) {
            try {
                a[i] = readInt();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return a;
    }

    int[] readSortedIntArray(int size) throws IOException {
        Integer[] array = new Integer[size];

        for (int index = 0; index < size; ++index) {
            array[index] = readInt();
        }
        Arrays.sort(array);

        int[] sortedArray = new int[size];
        for (int index = 0; index < size; ++index) {
            sortedArray[index] = array[index];
        }

        return sortedArray;
    }

    int[] sortedIntArray(int size, int[] array) throws IOException {
        for (int index = 0; index < size; ++index) {
            array[index] = readInt();
        }
        Arrays.sort(array);

        int[] sortedArray = new int[size];
        for (int index = 0; index < size; ++index) {
            sortedArray[index] = array[index];
        }

        return sortedArray;
    }

    int minInt(int... values) {
        int min = Integer.MAX_VALUE;
        for (int value : values) {
            min = Math.min(min, value);
        }
        return min;
    }

    int maxInt(int... values) {
        int max = Integer.MIN_VALUE;
        for (int value : values) {
            max = Math.max(max, value);
        }
        return max;
    }

    long minLong(long... values) {
        long min = Long.MAX_VALUE;
        for (long value : values) {
            min = Math.min(min, value);
        }
        return min;
    }

    long maxLong(long... values) {
        long max = Long.MIN_VALUE;
        for (long value : values) {
            max = Math.max(max, value);
        }
        return max;
    }

    boolean checkIndex(int index, int size) {
        return (0 <= index && index < size);
    }

    int abs(int a) {
        return Math.abs(a);
    }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Optional;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.TreeSet;
import java.io.InputStream;

/**
 * Built using CHelper plug-in Actual solution is at the top
 *
 * @author MaxHeap
 */
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);
    MaximumSubsequence solver = new MaximumSubsequence();
    solver.solve(1, in, out);
    out.close();
  }

  static class MaximumSubsequence {

    public void solve(int testNumber, InputReader in, PrintWriter out) {
      int n = in.nextInt(), m = in.nextInt();
      TreeSet<Integer> res = new TreeSet<>();
      int[] arr = in.nextIntArray(n);
      int half = n / 2;
      for (int mask = 0; mask < (1 << half); mask++) {
        int sum = 0;
        for (int j = 0; j < half; j++) {
          if ((mask & (1 << j)) != 0) {
            sum += (arr[j] % m);
            sum %= m;
          }
        }
        res.add(-sum);
      }
      int ohalf = n - half;
      int max = 0;
      for (int mask = 0; mask < (1 << ohalf); mask++) {
        int sum = 0;
        for (int j = 0; j < ohalf; j++) {
          if ((mask & (1 << j)) != 0) {
            sum += (arr[j + half] % m);
            sum %= m;
          }
        }
        Integer val = -Optional.ofNullable(res.higher(-(m - sum))).orElse(0);
        max = Math.max(max, sum + val);
      }
      out.println(max);
    }

  }

  static class InputReader {

    private InputStream stream;
    private byte[] buf = new byte[1 << 13];
    private int curChar;
    private int numChars;

    public InputReader(InputStream stream) {
      this.stream = stream;
    }

    public int read() {
      if (this.numChars == -1) {
        throw new UnknownError();
      } else {
        if (this.curChar >= this.numChars) {
          this.curChar = 0;

          try {
            this.numChars = this.stream.read(this.buf);
          } catch (IOException ex) {
            throw new InputMismatchException();
          }

          if (this.numChars <= 0) {
            return -1;
          }
        }

        return this.buf[this.curChar++];
      }
    }

    public int nextInt() {
      int c;
      for (c = this.read(); isSpaceChar(c); c = this.read()) {
      }

      byte sgn = 1;
      if (c == 45) {
        sgn = -1;
        c = this.read();
      }

      int res = 0;

      while (c >= 48 && c <= 57) {
        res *= 10;
        res += c - 48;
        c = this.read();
        if (isSpaceChar(c)) {
          return res * sgn;
        }
      }

      throw new InputMismatchException();
    }

    public static boolean isSpaceChar(int c) {
      return c == 32 || c == 10 || c == 13 || c == 9 || c == -1;
    }

    public int[] nextIntArray(int n) {
      int[] arr = new int[n];
      for (int i = 0; i < n; i++) {
        arr[i] = nextInt();
      }
      return arr;
    }

  }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.TreeSet;
import java.io.InputStream;

/**
 * Built using CHelper plug-in Actual solution is at the top
 *
 * @author MaxHeap
 */
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);
    MaximumSubsequence solver = new MaximumSubsequence();
    solver.solve(1, in, out);
    out.close();
  }

  static class MaximumSubsequence {

    public void solve(int testNumber, InputReader in, PrintWriter out) {
      int n = in.nextInt(), m = in.nextInt();
      TreeSet<Integer> res = new TreeSet<>();
      int[] arr = in.nextIntArray(n);
      int half = n / 2;
      for (int mask = 0; mask < (1 << half); mask++) {
        int sum = 0;
        for (int j = 0; j < half; j++) {
          if ((mask & (1 << j)) != 0) {
            sum += (arr[j] % m);
            sum %= m;
          }
        }
        res.add(-sum);
      }
      int ohalf = n - half;
      int max = 0;
      for (int mask = 0; mask < (1 << ohalf); mask++) {
        int sum = 0;
        for (int j = 0; j < ohalf; j++) {
          if ((mask & (1 << j)) != 0) {
            sum += (arr[j + half] % m);
            sum %= m;
          }
        }
        max = Math.max(max, sum + (res.higher(-(m - sum)) == null ? 0 : -res.higher(-(m - sum))));
      }
      out.println(max);
    }

  }

  static class InputReader {

    private InputStream stream;
    private byte[] buf = new byte[1 << 13];
    private int curChar;
    private int numChars;

    public InputReader(InputStream stream) {
      this.stream = stream;
    }

    public int read() {
      if (this.numChars == -1) {
        throw new UnknownError();
      } else {
        if (this.curChar >= this.numChars) {
          this.curChar = 0;

          try {
            this.numChars = this.stream.read(this.buf);
          } catch (IOException ex) {
            throw new InputMismatchException();
          }

          if (this.numChars <= 0) {
            return -1;
          }
        }

        return this.buf[this.curChar++];
      }
    }

    public int nextInt() {
      int c;
      for (c = this.read(); isSpaceChar(c); c = this.read()) {
      }

      byte sgn = 1;
      if (c == 45) {
        sgn = -1;
        c = this.read();
      }

      int res = 0;

      while (c >= 48 && c <= 57) {
        res *= 10;
        res += c - 48;
        c = this.read();
        if (isSpaceChar(c)) {
          return res * sgn;
        }
      }

      throw new InputMismatchException();
    }

    public static boolean isSpaceChar(int c) {
      return c == 32 || c == 10 || c == 13 || c == 9 || c == -1;
    }

    public int[] nextIntArray(int n) {
      int[] arr = new int[n];
      for (int i = 0; i < n; i++) {
        arr[i] = nextInt();
      }
      return arr;
    }

  }
}

/**
 * Created by Aminul on 11/28/2018.
 */

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

public class CF888E {
    public static void main(String[] args)throws Exception {
        FastReader in = new FastReader(System.in);
        PrintWriter pw = new PrintWriter(System.out);
        int n = in.nextInt(), m = in.nextInt();
        int arr[] = new int[n];
        for (int i = 0; i < n; i++) {
            arr[i] = in.nextInt() % m;
        }
        int a[] = solve(Arrays.copyOfRange(arr, 0, n/2), m);
        int b[] = solve(Arrays.copyOfRange(arr, (n/2), n), m);
        int max = 0;
        for(int i : a) {
            int need = m - 1 - i;
            int floor = floor(b, need);
            if(floor != -1) max = max(max, i + b[floor]);
        }
        for(int i : b) {
            int need = m - 1 - i;
            int floor = floor(a, need);
            if(floor != -1) max = max(max, i + a[floor]);
        }
        pw.println(max);
        pw.close();
    }

    static int[] solve(int a[], int mod) {
        int n = a.length;
        int res[] = new int[1 << n];
        for (int i = 0; i < (1 << n); i++) {
            int sum = 0;
            for(int j = 0; j < n; j++) {
                if(check(i, j)) {
                    sum += a[j];
                    if(sum >= mod) sum -= mod;
                }
            }
            res[i] = sum;
        }
        Arrays.sort(res);
        return res;
    }

    static int floor(int arr[], int key) {
        int lo = 0, hi = arr.length - 1, mid;
        while (lo < hi) {
            mid = (lo + hi) / 2;
            if (arr[mid] > key) hi = mid;
            else lo = mid + 1;
        }
        return (lo >= arr.length || arr[lo] > key) ? lo-1: lo;
        //returns right Most index where arr[lo] <= key
        //returns -1 if all values are greater than key
    }

    static boolean check(int N,int pos){return (N & (1<<pos)) != 0;}
    static int set(int N,int pos){return N=N | (1<<pos);}
    static int reset(int N,int pos){return N= N & ~(1<<pos);}

    static void debug(Object...obj) {
        System.err.println(Arrays.deepToString(obj));
    }

    static class FastReader {
        InputStream is;
        private byte[] inbuf = new byte[1024];
        private int lenbuf = 0, ptrbuf = 0;

        public FastReader(InputStream is) {
            this.is = is;
        }

        public int readByte() {
            if (lenbuf == -1) throw new InputMismatchException();
            if (ptrbuf >= lenbuf) {
                ptrbuf = 0;
                try {
                    lenbuf = is.read(inbuf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (lenbuf <= 0) return -1;
            }
            return inbuf[ptrbuf++];
        }

        public boolean isSpaceChar(int c) {
            return !(c >= 33 && c <= 126);
        }
        private boolean isEndOfLine(int c) {
            return c == '\n' || c == '\r' || c == -1;
        }

        public int skip() {
            int b;
            while ((b = readByte()) != -1 && isSpaceChar(b)) ;
            return b;
        }

        public String next() {
            int b = skip();
            StringBuilder sb = new StringBuilder();
            while (!(isSpaceChar(b))) {
                sb.appendCodePoint(b);
                b = readByte();
            }
            return sb.toString();
        }

        public String nextLine() {
            int c = skip();
            StringBuilder sb = new StringBuilder();
            while (!isEndOfLine(c)){
                sb.appendCodePoint(c);
                c = readByte();
            }
            return sb.toString();
        }

        public int nextInt() {
            int num = 0, b;
            boolean minus = false;
            while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
            if (b == '-') {
                minus = true;
                b = readByte();
            }
            while (true) {
                if (b >= '0' && b <= '9') {
                    num = (num << 3) + (num << 1) + (b - '0');
                } else {
                    return minus ? -num : num;
                }
                b = readByte();
            }
        }

        public long nextLong() {
            long num = 0;
            int b;
            boolean minus = false;
            while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
            if (b == '-') {
                minus = true;
                b = readByte();
            }

            while (true) {
                if (b >= '0' && b <= '9') {
                    num = (num << 3) + (num << 1) + (b - '0');
                } else {
                    return minus ? -num : num;
                }
                b = readByte();
            }
        }

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

        public char[] next(int n) {
            char[] buf = new char[n];
            int b = skip(), p = 0;
            while (p < n && !(isSpaceChar(b))) {
                buf[p++] = (char) b;
                b = readByte();
            }
            return n == p ? buf : Arrays.copyOf(buf, p);
        }

        public char readChar() {
            return (char) skip();
        }
    }
}

import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

/**
 * Created by shhuan on 2017/11/10.
 */
public class Main_888E {

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		int N = scanner.nextInt();
		int M = scanner.nextInt();

		scanner.nextLine();

		int[] A = Arrays.stream(scanner.nextLine().split(" ")).mapToInt(v -> Integer.parseInt(v)).toArray();

		if (N == 1){
			System.out.println(A[0] % M);
		} else {
			int lb = N / 2;
			int lc = N-lb;
			int[] B = new int[lb];
			int[] C = new int[lc];
			for (int i = 0; i < lb; i++) {
				B[i] = A[i];
			}
			for (int i = 0; i < lc; i++) {
				C[i] = A[i+lb];
			}

			Set<Integer> bs = new HashSet<>();
			bs.add(0);
			for (int i = 0; i < lb; i++) {
				Set<Integer> bd = new HashSet<>();
				for (Integer v : bs) {
					bd.add((v+B[i]) % M);
				}
				bs.addAll(bd);
			}

			Set<Integer> cs = new HashSet<>();
			cs.add(0);
			for (int i = 0; i < lc; i++) {
				Set<Integer> cd = new HashSet<>();
				for (Integer v : cs) {
					cd.add((v+C[i]) % M);
				}
				cs.addAll(cd);
			}

			int[] cs2 = cs.stream().mapToInt(v -> v).toArray();
			Arrays.sort(cs2);

			int ans = 0;
			for (int v: bs) {
				int k = 1;
				while (true) {
					int i = binary_search(cs2, k*M-v-1);
					if (i > 0) {
						ans = Math.max(ans, (v+cs2[i-1])%M);
					}
					if (0 <= i && i < cs2.length) {
						ans = Math.max(ans, (v+cs2[i]) % M);
					}
					if (i < 0 || i >= cs2.length) {
						break;
					}
					k += 1;
				}
			}

			System.out.println(ans);

		}
	}

	public static int binary_search(int[] A, int val) {
		int lo = 0;
		int hi = A.length;

		while (lo < hi) {
			int m = (lo + hi) / 2;
			if (A[m] == val) {
				return m;
			} else if (A[m] > val) {
				hi = m;
			} else {
				lo = m + 1;
			}
		}

		return lo;
	}
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;

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

    static class TaskE {
        int n;
        int m;
        int[] a;

        public void solve(int testNumber, InputReader in, OutputWriter out) {
            n = in.readInt();
            m = in.readInt();
            a = IOUtils.readIntArray(in, n);

            if (n == 1) {
                out.print(a[0] % m);
                return;
            }

            int leftSize = n / 2;
            int[] a1 = init(0, leftSize);
            int[] a2 = init(leftSize, n);
            int mx = a2[a2.length - 1];

            int best = 0;
            int j = a2.length - 1;
            for (int i : a1) {
                while (i + a2[j] >= m) {
                    j--;
                }
                best = Math.max(best, Math.max((i + mx) % m, (i + a2[j]) % m));
            }
            out.print(best);
        }

        int[] init(int l, int r) {
            int len = r - l;
            int[] values = new int[1 << len];
            for (int i = 1, j = 0; i < 1 << len; i++) {
                if (i == (1 << (j + 1))) {
                    j++;
                }
                values[i] = (values[i ^ (1 << j)] + a[l + j]) % m;
            }
            Arrays.sort(values);
            return values;
        }

    }

    static class IOUtils {
        public static int[] readIntArray(InputReader in, int size) {
            int[] array = new int[size];
            for (int i = 0; i < size; i++) {
                array[i] = in.readInt();
            }
            return array;
        }

    }

    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private InputReader.SpaceCharFilter filter;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars == -1) {
                throw new InputMismatchException();
            }
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (numChars <= 0) {
                    return -1;
                }
            }
            return buf[curChar++];
        }

        public int readInt() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9') {
                    throw new InputMismatchException();
                }
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public boolean isSpaceChar(int c) {
            if (filter != null) {
                return filter.isSpaceChar(c);
            }
            return isWhitespace(c);
        }

        public static boolean isWhitespace(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);

        }

    }

    static class OutputWriter {
        private final PrintWriter writer;

        public OutputWriter(OutputStream outputStream) {
            writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
        }

        public OutputWriter(Writer writer) {
            this.writer = new PrintWriter(writer);
        }

        public void close() {
            writer.close();
        }

        public void print(int i) {
            writer.print(i);
        }

    }
}

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

public final class ms
{
    static BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
	static FastScanner sc=new FastScanner(br);
    static PrintWriter out=new PrintWriter(System.out);
	static Random rnd=new Random();
	static List<Long> list;

	static long get(long curr,long mod)
	{
		int low=0,high=list.size()-1;

		while(low<high)
		{
			int mid=(low+high+1)>>1;

			if(list.get(mid)+curr<mod)
			{
				low=mid;
			}
			else
			{
				high=mid-1;
			}
		}

		return list.get(low);
	}

    public static void main(String args[]) throws Exception
    {
		int n=sc.nextInt();long mod=sc.nextLong();

		long[] a=new long[n];

		for(int i=0;i<n;i++)
		{
			a[i]=sc.nextLong();
		}

		int x=Math.min(n,18),y=17;

		long[] arr1=new long[x],arr2=new long[y];

		for(int i=0;i<x;i++)
		{
			arr1[i]=a[i];
		}

		for(int i=x;i<n;i++)
		{
			arr2[i-x]=a[i];
		}

		list=new ArrayList<>();list.add(0L);

		for(int i=0;i<(1<<y);i++)
		{
			long sum=0;

			for(int j=0;j<y;j++)
			{
				if((i&(1<<j))!=0)
				{
					sum=(sum+arr2[j])%mod;
				}
			}

			list.add(sum);
		}

		Collections.sort(list);long max=0;

		for(int i=0;i<(1<<x);i++)
		{
			long curr=0;

			for(int j=0;j<x;j++)
			{
				if((i&(1<<j))!=0)
				{
					curr=(curr+arr1[j])%mod;
				}
			}

			long now1=(curr+get(curr,mod))%mod,now2=(curr+list.get(list.size()-1))%mod;

			max=Math.max(max,Math.max(now1,now2));
		}

		out.println(max);out.close();
    }
}
class FastScanner
{
    BufferedReader in;
    StringTokenizer st;

    public FastScanner(BufferedReader in) {
        this.in = in;
    }

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

	public String next() throws Exception {
		return nextToken().toString();
	}

    public int nextInt() throws Exception {
        return Integer.parseInt(nextToken());
    }

    public long nextLong() throws Exception {
        return Long.parseLong(nextToken());
    }

    public double nextDouble() throws Exception {
        return Double.parseDouble(nextToken());
    }
}

import java.util.*;
import java.io.*;
import java.math.*;
public class smack {
	InputStream is;
	PrintWriter out;
	int dx[]= {0,0,1,-1},dy[]={+1,-1,0,0};
	static long mod=pow(10,9)+7;
	void solve()
	{
		int n=ni();
		long k=nl();
		long a[]=new long[n];
		for(int i=0;i<n;i++)
			a[i]=nl();
		int index=n/2;
		TreeSet<Long> ts=new TreeSet<Long>();
		ArrayList<Long> al=new ArrayList<Long>();
		for(int i=0;i<(1<<index);i++)
		{
			long ans=0;
			for(int j=0;j<index;j++)
			{
				if((i&(1<<j))!=0)
					ans+=a[j];
			}
			ts.add(ans%k);
		}
		int total=n-index;
		long max=0;
		for(int i=0;i<(1<<total);i++)
		{
			long ans=0;
			for(int j=0;j<total;j++)
			{
				if((i&(1<<j))!=0)
					ans+=a[j+index];
			}
			ans%=k;
			Long get=ts.floor(k-ans-1);
			if(get!=null)
				max=Math.max(max,get+ans);
		}
		out.println(max);
	}
	boolean check(int mid,String s)
	{
	outer:	for(int i=0;i<26;i++)
		{
			char ch=(char)(i+'a');
			int count=0;
			for(int j=0;j<mid;j++)
			{
				if(ch==s.charAt(j))
					count++;
			}
			if(count==0)
				continue;
			for(int j=1;j<s.length()-mid+1;j++)
			{
				if(s.charAt(j-1)==ch)
					count--;
				if(s.charAt(j+mid-1)==ch)
					count++;
				if(count==0)
					continue outer;
			}
			return true;
		}
		return false;
	}
	int small[];
	void pre(int n)
	{
		small=new int[n+1];
		for(int i=2;i*i<=n;i++)
		{
			for(int j=i;j*i<=n;j++)
			{
				if(small[i*j]==0)
					small[i*j]=i;
			}
		}
		for(int i=0;i<=n;i++)
		{
			if(small[i]==0)
				small[i]=i;
		}
	}
	static long d, x, y;
	void extendedEuclid(long A, long B) {
	    if(B == 0) {
	        d = A;
	        x = 1;
	        y = 0;
	    }
	    else {
	        extendedEuclid(B, A%B);
	        long temp = x;
	        x = y;
	        y = temp - (A/B)*y;
	    }
	}
	long modInverse(long A,long M) //A and M are coprime
	{
	    extendedEuclid(A,M);
	    return (x%M+M)%M;    //x may be negative
	}
	public static void mergeSort(int[] arr, int l ,int r){
		if((r-l)>=1){
			int mid = (l+r)/2;
			mergeSort(arr,l,mid);
			mergeSort(arr,mid+1,r);
			merge(arr,l,r,mid);
		}
	}
	public static void merge(int arr[], int l, int r, int mid){
		int n1 = (mid-l+1), n2 = (r-mid);
		int left[] = new int[n1];
		int right[] = new int[n2];
		for(int i =0 ;i<n1;i++) left[i] = arr[l+i];
		for(int i =0 ;i<n2;i++) right[i] = arr[mid+1+i];
		int i =0, j =0, k = l;
		while(i<n1 && j<n2){
			if(left[i]>right[j]){
				arr[k++] = right[j++];
			}
			else{
				arr[k++] = left[i++];
			}
		}
		while(i<n1) arr[k++] = left[i++];
		while(j<n2) arr[k++] = right[j++];
	}
	public static void mergeSort(long[] arr, int l ,int r){
		if((r-l)>=1){
			int mid = (l+r)/2;
			mergeSort(arr,l,mid);
			mergeSort(arr,mid+1,r);
			merge(arr,l,r,mid);
		}
	}
	public static void merge(long arr[], int l, int r, int mid){
		int n1 = (mid-l+1), n2 = (r-mid);
		long left[] = new long[n1];
		long right[] = new long[n2];
		for(int i =0 ;i<n1;i++) left[i] = arr[l+i];
		for(int i =0 ;i<n2;i++) right[i] = arr[mid+1+i];
		int i =0, j =0, k = l;
		while(i<n1 && j<n2){
			if(left[i]>right[j]){
				arr[k++] = right[j++];
			}
			else{
				arr[k++] = left[i++];
			}
		}
		while(i<n1) arr[k++] = left[i++];
		while(j<n2) arr[k++] = right[j++];
	}
	 static class Pair implements Comparable<Pair>{

	       int x,y,k;
	       int i,dir;
	       long cost;
		Pair (int x,int y){
			this.x=x;
			this.y=y;
		}
		public int compareTo(Pair o) {
			if(this.y!=o.y)
				return this.y-o.y;
			return this.x-o.x;
		}

		public String toString(){
			return x+" "+y+" "+k+" "+i;}
		public boolean equals(Object o) {
			if (o instanceof Pair) {
				Pair p = (Pair)o;
				return p.x == x && p.y == y;
			}
			return false;
		}
		public int hashCode() {
			return new Long(y).hashCode()*31 + new Long(x).hashCode() ;
		}
	}
	    public static boolean isPal(String s){
	        for(int i=0, j=s.length()-1;i<=j;i++,j--){
	                if(s.charAt(i)!=s.charAt(j)) return false;
	        }
	        return true;
	    }
	    public static String rev(String s){
			StringBuilder sb=new StringBuilder(s);
			sb.reverse();
			return sb.toString();
	    }

	    public static long gcd(long x,long y){
		if(x%y==0)
			return y;
		else
			return gcd(y,x%y);
	    }

	    public static int gcd(int x,int y){
		if(y==0)
			return x;
		else
			return gcd(y,x%y);
	    }

	    public static long gcdExtended(long a,long b,long[] x){

	        if(a==0){
	            x[0]=0;
	            x[1]=1;
	            return b;
	        }
	        long[] y=new long[2];
	        long gcd=gcdExtended(b%a, a, y);

	        x[0]=y[1]-(b/a)*y[0];
	        x[1]=y[0];

	        return gcd;
	    }

	    public static int abs(int a,int b){
		return (int)Math.abs(a-b);
	    }

	    public static long abs(long a,long b){
		return (long)Math.abs(a-b);
	    }

	    public static int max(int a,int b){
		if(a>b)
			return a;
		else
			return b;
	    }

	    public static int min(int a,int b){
		if(a>b)
			return b;
		else
			return a;
	    }

	    public static long max(long a,long b){
		if(a>b)
			return a;
		else
			return b;
	    }

	    public static long min(long a,long b){
		if(a>b)
			return b;
		else
			return a;
	    }

	    public static long pow(long n,long p,long m){
		 long  result = 1;
		  if(p==0)
		    return 1;
		if (p==1)
		    return n;
		while(p!=0)
		{
		    if(p%2==1)
		        result *= n;
		    if(result>=m)
		    result%=m;
		    p >>=1;
		    n*=n;
		    if(n>=m)
		    n%=m;
		}
		return result;
	    }

	    public 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;
	    }
	    public static void debug(Object... o) {
			System.out.println(Arrays.deepToString(o));
		}
	    void run() throws Exception {
			is = System.in;
			out = new PrintWriter(System.out);
			solve();
			out.flush();
		}

	    public static void main(String[] args) throws Exception {
			new Thread(null, new Runnable() {
				public void run() {
					try {
						new smack().run();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}, "1", 1 << 26).start();
		}
	    private byte[] inbuf = new byte[1024];
		public int lenbuf = 0, ptrbuf = 0;

		private int readByte() {
			if (lenbuf == -1)
				throw new InputMismatchException();
			if (ptrbuf >= lenbuf) {
				ptrbuf = 0;
				try {
					lenbuf = is.read(inbuf);
				} catch (IOException e) {
					throw new InputMismatchException();
				}
				if (lenbuf <= 0)
					return -1;
			}
			return inbuf[ptrbuf++];
		}

		private boolean isSpaceChar(int c) {
			return !(c >= 33 && c <= 126);
		}

		private int skip() {
			int b;
			while ((b = readByte()) != -1 && isSpaceChar(b));
			return b;
		}

		private double nd() {
			return Double.parseDouble(ns());
		}

		private char nc() {
			return (char) skip();
		}

		private String ns() {
			int b = skip();
			StringBuilder sb = new StringBuilder();
			while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ')
				sb.appendCodePoint(b);
				b = readByte();
			}
			return sb.toString();
		}

		private char[] ns(int n) {
			char[] buf = new char[n];
			int b = skip(), p = 0;
			while (p < n && !(isSpaceChar(b))) {
				buf[p++] = (char) b;
				b = readByte();
			}
			return n == p ? buf : Arrays.copyOf(buf, p);
		}

		private char[][] nm(int n, int m) {
			char[][] map = new char[n][];
			for (int i = 0; i < n; i++)
				map[i] = ns(m);
			return map;
		}

		private int[] na(int n) {
			int[] a = new int[n];
			for (int i = 0; i < n; i++)
				a[i] = ni();
			return a;
		}

		private int ni() {
			int num = 0, b;
			boolean minus = false;
			while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
				;
			if (b == '-') {
				minus = true;
				b = readByte();
			}

			while (true) {
				if (b >= '0' && b <= '9') {
					num = num * 10 + (b - '0');
				} else {
					return minus ? -num : num;
				}
				b = readByte();
			}
		}

		private long nl() {
			long num = 0;
			int b;
			boolean minus = false;
			while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
				;
			if (b == '-') {
				minus = true;
				b = readByte();
			}

			while (true) {
				if (b >= '0' && b <= '9') {
					num = num * 10 + (b - '0');
				} else {
					return minus ? -num : num;
				}
				b = readByte();
			}
		}

}

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

import static java.util.Arrays.fill;
import static java.lang.Math.*;
import static java.util.Arrays.sort;
import static java.util.Collections.sort;

public class MaximumSubsequence {

	public static int mod = 1000000007;
	public static long INF = (1L << 60);
	static FastScanner2 in = new FastScanner2();
	static OutputWriter out = new OutputWriter(System.out);

	public static void main(String[] args) {

		int n=in.nextInt();
		int m=in.nextInt();
		int[] a=new int[n/2];
		int[] b=new int[(n+1)/2];
		for(int i=0;i<n/2;i++)
		{
			a[i]=in.nextInt();
		}
		for(int i=0;i<(n+1)/2;i++)
		{
			b[i]=in.nextInt();
		}
		int ans=0;
		int[] set1=new int[(1<<(n/2))+1];
		int[] set2=new int[(1<<(n+1)/2)+1];
		for(int i=0;i<(1<<(n/2));i++)
		{
			int temp=0;
			for(int j=0;j<n/2;j++)
			{
				if((i&(1<<j))>0)
				{
					temp+=a[j];
					temp%=m;
				}
			}
			ans=max(ans, temp);
			set1[i]=temp;
		}
		for(int i=0;i<(1<<(n+1)/2);i++)
		{
			int temp=0;
			for(int j=0;j<(n+1)/2;j++)
			{
				if((i&(1<<j))>0)
				{
					temp+=b[j];
					temp%=m;
				}
			}
			ans=max(ans, temp);
			set2[i]=temp;
		}
		Arrays.sort(set2);
		for(int i=0;i<set1.length;i++)
		{
			int l=0;
			int r=set2.length-1;
			int x1=set1[i];
			while(l<=r)
			{
				int mid=(l+r)/2;
				int x2=set2[mid];
				if(x1+x2>m)
				{
					ans=max(ans, (x1+x2)%m);
					r=mid-1;
				}
				else
				{
					ans=max(ans, (x1+x2)%m);
					l=mid+1;
				}
			}
			ans=max(ans, (x1+set2[set2.length-1])%m);
		}
		out.println(ans);

		out.close();

	}

	static class FastScanner2 {
		private byte[] buf = new byte[1024];
		private int curChar;
		private int snumChars;

		public int read() {
			if (snumChars == -1)
				throw new InputMismatchException();
			if (curChar >= snumChars) {
				curChar = 0;
				try {
					snumChars = System.in.read(buf);
				} catch (IOException e) {
					throw new InputMismatchException();
				}
				if (snumChars <= 0)
					return -1;
			}
			return buf[curChar++];
		}

		public String nextLine() {
			int c = read();
			while (isSpaceChar(c))
				c = read();
			StringBuilder res = new StringBuilder();
			do {
				res.appendCodePoint(c);
				c = read();
			} while (!isEndOfLine(c));
			return res.toString();
		}

		public String nextString() {
			int c = read();
			while (isSpaceChar(c))
				c = read();
			StringBuilder res = new StringBuilder();
			do {
				res.appendCodePoint(c);
				c = read();
			} while (!isSpaceChar(c));
			return res.toString();
		}

		public long nextLong() {
			int c = read();
			while (isSpaceChar(c))
				c = read();
			int sgn = 1;
			if (c == '-') {
				sgn = -1;
				c = read();
			}
			long res = 0;
			do {
				if (c < '0' || c > '9')
					throw new InputMismatchException();
				res *= 10;
				res += c - '0';
				c = read();
			} while (!isSpaceChar(c));
			return res * sgn;
		}

		public int nextInt() {
			int c = read();
			while (isSpaceChar(c))
				c = read();
			int sgn = 1;
			if (c == '-') {
				sgn = -1;
				c = read();
			}
			int res = 0;
			do {
				if (c < '0' || c > '9')
					throw new InputMismatchException();
				res *= 10;
				res += c - '0';
				c = read();
			} while (!isSpaceChar(c));
			return res * sgn;
		}

		public int[] nextIntArray(int n) {
			int[] arr = new int[n];
			for (int i = 0; i < n; i++) {
				arr[i] = nextInt();
			}
			return arr;
		}

		public long[] nextLongArray(int n) {
			long[] arr = new long[n];
			for (int i = 0; i < n; i++) {
				arr[i] = nextLong();
			}
			return arr;
		}

		private boolean isSpaceChar(int c) {
			return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
		}

		private boolean isEndOfLine(int c) {
			return c == '\n' || c == '\r' || c == -1;
		}
	}

	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[] nextIntArray(int n) {
			int a[] = new int[n];
			for (int i = 0; i < n; i++) {
				a[i] = nextInt();
			}
			return a;
		}

		public long[] nextLongArray(int n) {
			long a[] = new long[n];
			for (int i = 0; i < n; i++) {
				a[i] = nextLong();
			}
			return a;
		}

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

	static class OutputWriter {
		private final PrintWriter writer;

		public OutputWriter(OutputStream outputStream) {
			writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
		}

		public OutputWriter(Writer writer) {
			this.writer = new PrintWriter(writer);
		}

		public void print(Object... objects) {
			for (int i = 0; i < objects.length; i++) {
				if (i != 0)
					writer.print(' ');
				writer.print(objects[i]);
			}
		}

		public void println(Object... objects) {
			print(objects);
			writer.println();
		}

		public void close() {
			writer.close();
		}

		public void flush() {
			writer.flush();
		}
	}

	private static boolean oj = System.getProperty("ONLINE_JUDGE") != null;

	private static void debug(Object... o) {
		if (!oj)
			System.out.println(Arrays.deepToString(o));
	}

	private static void tr(Object... o) {
		if (!oj)
			System.out.println(Arrays.deepToString(o));
	}
}

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

import static java.util.Arrays.fill;
import static java.lang.Math.*;
import static java.util.Arrays.sort;
import static java.util.Collections.sort;

public class MaximumSubsequence {

	public static int mod = 1000000007;
	public static long INF = (1L << 60);
	static FastScanner2 in = new FastScanner2();
	static OutputWriter out = new OutputWriter(System.out);

	public static void main(String[] args) {

		int n=in.nextInt();
		int m=in.nextInt();
		int[] a=new int[n/2];
		int[] b=new int[(n+1)/2];
		for(int i=0;i<n/2;i++)
		{
			a[i]=in.nextInt();
		}
		for(int i=0;i<(n+1)/2;i++)
		{
			b[i]=in.nextInt();
		}
		int ans=0;
		int[] set1=new int[(1<<(n/2))+1];
		int[] set2=new int[(1<<(n+1)/2)+1];
		for(int i=0;i<(1<<(n/2));i++)
		{
			int temp=0;
			for(int j=0;j<n/2;j++)
			{
				if((i&(1<<j))>0)
				{
					temp+=a[j];
					temp%=m;
				}
			}
			ans=max(ans, temp);
			set1[i]=temp;
		}
		for(int i=0;i<(1<<(n+1)/2);i++)
		{
			int temp=0;
			for(int j=0;j<(n+1)/2;j++)
			{
				if((i&(1<<j))>0)
				{
					temp+=b[j];
					temp%=m;
				}
			}
			ans=max(ans, temp);
			set2[i]=temp;
		}
		Arrays.sort(set2);
		for(int i=0;i<set1.length;i++)
		{
			int l=0;
			int r=set2.length-1;
			int x1=set1[i];
			while(l<=r)
			{
				int mid=(l+r)/2;
				int x2=set2[mid];
				if(x1+x2>m)
				{
					ans=max(ans, (x1+x2)%m);
					r=mid-1;
				}
				else
				{
					ans=max(ans, (x1+x2)%m);
					l=mid+1;
				}
			}
		}
		out.println(ans);

		out.close();

	}

	static class FastScanner2 {
		private byte[] buf = new byte[1024];
		private int curChar;
		private int snumChars;

		public int read() {
			if (snumChars == -1)
				throw new InputMismatchException();
			if (curChar >= snumChars) {
				curChar = 0;
				try {
					snumChars = System.in.read(buf);
				} catch (IOException e) {
					throw new InputMismatchException();
				}
				if (snumChars <= 0)
					return -1;
			}
			return buf[curChar++];
		}

		public String nextLine() {
			int c = read();
			while (isSpaceChar(c))
				c = read();
			StringBuilder res = new StringBuilder();
			do {
				res.appendCodePoint(c);
				c = read();
			} while (!isEndOfLine(c));
			return res.toString();
		}

		public String nextString() {
			int c = read();
			while (isSpaceChar(c))
				c = read();
			StringBuilder res = new StringBuilder();
			do {
				res.appendCodePoint(c);
				c = read();
			} while (!isSpaceChar(c));
			return res.toString();
		}

		public long nextLong() {
			int c = read();
			while (isSpaceChar(c))
				c = read();
			int sgn = 1;
			if (c == '-') {
				sgn = -1;
				c = read();
			}
			long res = 0;
			do {
				if (c < '0' || c > '9')
					throw new InputMismatchException();
				res *= 10;
				res += c - '0';
				c = read();
			} while (!isSpaceChar(c));
			return res * sgn;
		}

		public int nextInt() {
			int c = read();
			while (isSpaceChar(c))
				c = read();
			int sgn = 1;
			if (c == '-') {
				sgn = -1;
				c = read();
			}
			int res = 0;
			do {
				if (c < '0' || c > '9')
					throw new InputMismatchException();
				res *= 10;
				res += c - '0';
				c = read();
			} while (!isSpaceChar(c));
			return res * sgn;
		}

		public int[] nextIntArray(int n) {
			int[] arr = new int[n];
			for (int i = 0; i < n; i++) {
				arr[i] = nextInt();
			}
			return arr;
		}

		public long[] nextLongArray(int n) {
			long[] arr = new long[n];
			for (int i = 0; i < n; i++) {
				arr[i] = nextLong();
			}
			return arr;
		}

		private boolean isSpaceChar(int c) {
			return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
		}

		private boolean isEndOfLine(int c) {
			return c == '\n' || c == '\r' || c == -1;
		}
	}

	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[] nextIntArray(int n) {
			int a[] = new int[n];
			for (int i = 0; i < n; i++) {
				a[i] = nextInt();
			}
			return a;
		}

		public long[] nextLongArray(int n) {
			long a[] = new long[n];
			for (int i = 0; i < n; i++) {
				a[i] = nextLong();
			}
			return a;
		}

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

	static class OutputWriter {
		private final PrintWriter writer;

		public OutputWriter(OutputStream outputStream) {
			writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
		}

		public OutputWriter(Writer writer) {
			this.writer = new PrintWriter(writer);
		}

		public void print(Object... objects) {
			for (int i = 0; i < objects.length; i++) {
				if (i != 0)
					writer.print(' ');
				writer.print(objects[i]);
			}
		}

		public void println(Object... objects) {
			print(objects);
			writer.println();
		}

		public void close() {
			writer.close();
		}

		public void flush() {
			writer.flush();
		}
	}

	private static boolean oj = System.getProperty("ONLINE_JUDGE") != null;

	private static void debug(Object... o) {
		if (!oj)
			System.out.println(Arrays.deepToString(o));
	}

	private static void tr(Object... o) {
		if (!oj)
			System.out.println(Arrays.deepToString(o));
	}
}

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

public class Main implements Runnable {
    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private SpaceCharFilter filter;
        private BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars==-1)
                throw new InputMismatchException();

            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                }
                catch (IOException e) {
                    throw new InputMismatchException();
                }

                if(numChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }

        public String nextLine() {
            String str = "";
            try {
                str = br.readLine();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }
        public int nextInt() {
            int c = read();

            while(isSpaceChar(c))
                c = read();

            int sgn = 1;

            if (c == '-') {
                sgn = -1;
                c = read();
            }

            int res = 0;
            do {
                if(c<'0'||c>'9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            }
            while (!isSpaceChar(c));

            return res * sgn;
        }

        public long nextLong() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            long res = 0;

            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            }
            while (!isSpaceChar(c));
            return res * sgn;
        }

        public double nextDouble() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            double res = 0;
            while (!isSpaceChar(c) && c != '.') {
                if (c == 'e' || c == 'E')
                    return res * Math.pow(10, nextInt());
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            }
            if (c == '.') {
                c = read();
                double m = 1;
                while (!isSpaceChar(c)) {
                    if (c == 'e' || c == 'E')
                        return res * Math.pow(10, nextInt());
                    if (c < '0' || c > '9')
                        throw new InputMismatchException();
                    m /= 10;
                    res += (c - '0') * m;
                    c = read();
                }
            }
            return res * sgn;
        }

        public String readString() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            StringBuilder res = new StringBuilder();
            do {
                res.appendCodePoint(c);
                c = read();
            }
            while (!isSpaceChar(c));

            return res.toString();
        }

        public boolean isSpaceChar(int c) {
            if (filter != null)
                return filter.isSpaceChar(c);
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public String next() {
            return readString();
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);
        }
    }
    public static void main(String args[]) throws Exception {
        new Thread(null, new Main(),"Main",1<<26).start();
    }

    static long gcd(long a,long b){ if(b==0)return a;return gcd(b,a%b); }
    static long modPow(long a,long p,long m){ if(a==1)return 1;long ans=1;while (p>0){ if(p%2==1)ans=(ans*a)%m;a=(a*a)%m;p>>=1; }return ans; }
    static long modInv(long a,long m){return modPow(a,m-2,m);}

    public void run() {
        InputReader sc = new InputReader(System.in);
        PrintWriter out = new PrintWriter(System.out);

        int n=sc.nextInt();
        int k=sc.nextInt();
        int a[]=new int[n];
        for (int i = 0; i <n ; i++) {
            a[i]=sc.nextInt();
        }
        int N_Half=n/2;
        long firsthalf[]=new long[1<<N_Half];
        for (int i = 0; i <(1<<N_Half) ; i++) {
            for (int j = 0; j <N_Half ; j++) {
                if((i&(1<<j))!=0){
                    firsthalf[i]+=a[j];
                }
            }
            firsthalf[i]%=k;
        }
        Arrays.sort(firsthalf);

        long maainans=Long.MIN_VALUE;
        for (int i = 0; i <1<<(n-N_Half) ; i++) {
            long temp=0;
            for (int j = 0; j <(n-N_Half) ; j++) {
                if((i&(1<<j))!=0){
                    temp+=a[j+N_Half];
                }
            }
            temp%=k;
            int l=0,r=(1<<N_Half)-1;long want=k-temp-1,ans=0;
            while (l<=r){
                int mid=(l+r)>>1;
                if(firsthalf[mid]<=want){
                    ans=firsthalf[mid];
                    l=mid+1;
                }
                else{
                    r=mid-1;
                }
            }
            maainans=Math.max(maainans,ans+temp);
        }

        out.println(maainans);

        out.close();
    }

}

/**
 * DA-IICT
 * Author : Savaliya Sagar
 */
import java.io.*;
import java.math.*;
import java.util.*;

import static java.util.Arrays.fill;
import static java.lang.Math.*;
import static java.util.Arrays.sort;
import static java.util.Collections.sort;

public class E888
{
	InputStream is;
	PrintWriter out;
	String INPUT = "";

	void solve()
	{
		int n = ni();
		int m = ni();
		int a[] = na(n);
		ArrayList<Long> l = new ArrayList<>();
		ArrayList<Long> r = new ArrayList<>();
		int le = n/2;
		int re = n - n/2;
		for(int i=0;i<(1<<le);i++) {
			long sum = 0;
			for(int j=0;j<le;j++) {
				if(((i>>j)&1)==1)
					sum += a[j];
			}
			l.add(sum%m);
		}
		for(int i=0;i<(1<<re);i++) {
			long sum = 0;
			for(int j=0;j<re;j++) {
				if(((i>>j)&1)==1)
					sum += a[le+j];
			}
			r.add(sum%m);
		}
		sort(r);
		long ans = 0;
		for(int i=0;i<l.size();i++) {
			long  t = l.get(i) + bs(r,m-1-l.get(i));
			ans = max(ans,t%m);
		}
		out.println(ans);
	}
	long bs(ArrayList<Long> a,long k) {
		int l =0;
		int r = a.size()-1;
		long ans = 0;
		while(l<=r) {
			int mid = (l+r)/2;
			if(a.get(mid)<=k)
			{
				ans = a.get(mid);
				l = mid+1;
			}else
				r = mid - 1;
		}
		return ans;
	}
	private int[] na(int n)
	{
		int[] a = new int[n];
		for (int i = 0; i < n; i++)
			a[i] = ni();
		return a;
	}
	void run() throws Exception
	{
		is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
		out = new PrintWriter(System.out);

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

	public static void main(String[] args) throws Exception
	{
		new Thread(null, new Runnable()
		{
			public void run()
			{
				try
				{
					new E888().run();
				} catch (Exception e)
				{
					e.printStackTrace();
				}
			}
		}, "1", 1 << 26).start();
	}

	private byte[] inbuf = new byte[1024];
	public int lenbuf = 0, ptrbuf = 0;

	private int readByte()
	{
		if (lenbuf == -1)
			throw new InputMismatchException();
		if (ptrbuf >= lenbuf)
		{
			ptrbuf = 0;
			try
			{
				lenbuf = is.read(inbuf);
			} catch (IOException e)
			{
				throw new InputMismatchException();
			}
			if (lenbuf <= 0)
				return -1;
		}
		return inbuf[ptrbuf++];
	}

	private boolean isSpaceChar(int c)
	{
		return !(c >= 33 && c <= 126);
	}

	private int skip()
	{
		int b;
		while ((b = readByte()) != -1 && isSpaceChar(b))
			;
		return b;
	}

	private double nd()
	{
		return Double.parseDouble(ns());
	}

	private char nc()
	{
		return (char) skip();
	}

	private String ns()
	{
		int b = skip();
		StringBuilder sb = new StringBuilder();
		while (!(isSpaceChar(b)))
		{ // when nextLine, (isSpaceChar(b) && b !=
			// ' ')
			sb.appendCodePoint(b);
			b = readByte();
		}
		return sb.toString();
	}

	private char[] ns(int n)
	{
		char[] buf = new char[n];
		int b = skip(), p = 0;
		while (p < n && !(isSpaceChar(b)))
		{
			buf[p++] = (char) b;
			b = readByte();
		}
		return n == p ? buf : Arrays.copyOf(buf, p);
	}

	private char[][] nm(int n, int m)
	{
		char[][] map = new char[n][];
		for (int i = 0; i < n; i++)
			map[i] = ns(m);
		return map;
	}

	private int ni()
	{
		int num = 0, b;
		boolean minus = false;
		while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
			;
		if (b == '-')
		{
			minus = true;
			b = readByte();
		}

		while (true)
		{
			if (b >= '0' && b <= '9')
			{
				num = num * 10 + (b - '0');
			} else
			{
				return minus ? -num : num;
			}
			b = readByte();
		}
	}

	private long nl()
	{
		long num = 0;
		int b;
		boolean minus = false;
		while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
			;
		if (b == '-')
		{
			minus = true;
			b = readByte();
		}

		while (true)
		{
			if (b >= '0' && b <= '9')
			{
				num = num * 10 + (b - '0');
			} else
			{
				return minus ? -num : num;
			}
			b = readByte();
		}
	}

	private void tr(Object... o)
	{
		System.out.println(Arrays.deepToString(o));
	}
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;

import static java.lang.Long.bitCount;

public class Main {

    public static void main(String[] args) {
        FastScanner in = new FastScanner();
        int N;
        long M;
        N = in.nextInt();
        M = in.nextInt();
        long []a = new long[N/2];
        long []b = new long[N-N/2];
        for(int i=0; i<N/2; ++i) a[i] = in.nextInt();
        for(int i=0; i<(N-N/2); ++i) b[i] = in.nextInt();

        long []c = new long[(1<<(N/2))];
        long []d = new long[(1<<(N-N/2))];

        for(int i=0; i<(1<<(N/2)); ++i){
            long l = 0;
            for(int j=0; j<N/2; ++j){
                if((i&(1<<j)) != 0){
                    l += a[j];
                }
            }
            c[i] = l%M;
        }

        TreeSet<Long> ar = new TreeSet<Long>();
        for(long x: c){
            ar.add(x%M);
        }
        Long []e = new Long[ar.size()];
        int t = 0;
        for(long x: ar){
            e[t] = x;
            ++t;
        }

        for(int i=0; i<(1<<(N-N/2)); ++i){
            long l = 0;
            for(int j=0; j<(N-N/2); ++j){
                if((i&(1<<j)) != 0){
                    l += b[j];
                }
            }
            d[i] = l%M;
        }

        TreeSet<Long> ar2 = new TreeSet<Long>();
        for(long x: d){
            ar2.add(x%M);
        }
        Long []f = new Long[ar2.size()];
        t = 0;
        for(long x: ar2){
            f[t] = x;
            ++t;
        }

        long MAX_ANS = 0;
        long s1 = e.length, s2 = f.length;

        for (long value : e) {
            long v1 = (M - value)%M;
            long v2 = ((M * 2) - value) % M;
            try{
                if(v1==0 && value == 0) continue;
                long got = ar2.lower(v1);
                long ans = (got+value)%M;
                MAX_ANS = Math.max(MAX_ANS, ans);
            }
            catch (Exception r) {
                System.out.println(0);
                System.exit(0);
            }
            try{
                if(v2==0 && value == 0) continue;
                long got = ar2.lower(v2);
                long ans = (got+value)%M;
                MAX_ANS = Math.max(MAX_ANS, ans);
            }
            catch (Exception r) {
                System.out.println(0);
                System.exit(0);
            }
        }

        for (long value : f) {
            long v1 = (M - value)%M;
            long v2 = ((M * 2) - value) % M;
            try{
                if(v1==0 && value == 0) continue;
                long got = ar.lower(v1);
                long ans = (got+value)%M;
                MAX_ANS = Math.max(MAX_ANS, ans);
            }
            catch (Exception r) {
                System.out.println(0);
                System.exit(0);
            }
            try{
                if(v2==0 && value == 0) continue;
                long got = ar.lower(v2);
                long ans = (got+value)%M;
                MAX_ANS = Math.max(MAX_ANS, ans);
            }
            catch (Exception r) {
                System.out.println(0);
                System.exit(0);
            }
        }

        System.out.println(MAX_ANS);
    }

    static void sort(int[] a) {
        ArrayList<Integer> l=new ArrayList<>();
        for (int i:a) l.add(i);
        Collections.sort(l);
        for (int i=0; i<a.length; i++) a[i]=l.get(i);
    }

    static class FastScanner {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st=new StringTokenizer("");
        String next() {
            while (!st.hasMoreTokens())
                try {
                    st=new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            return st.nextToken();
        }

        int nextInt() {
            return Integer.parseInt(next());
        }
        int[] readArray(int n) {
            int[] a=new int[n];
            for (int i=0; i<n; i++) a[i]=nextInt();
            return a;
        }
        long nextLong() {
            return Long.parseLong(next());
        }

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

/*
Fact :
   let x1 = n1%m
       x2 = n2%m;
   if((x1+x2)>=m)
      then (x1+x2)%m <= max(x1,x2);
this is why for a given number x we are searching a number less than or equal to (m-x)
*/
import java.util.*;
import java.io.*;
public class lp1{
static PrintWriter out = new PrintWriter(System.out);

static void fun(int a[],int is,int in,long sum,ArrayList<Long> arr,int m)
{
        if(is==in)
           {
              arr.add(sum);
              return;
           }
         fun(a,is+1,in,(sum+a[is])%m,arr,m);
         fun(a,is+1,in,sum,arr,m);
}
public static void main(String[] args){

int n = ni();
int m = ni();
int a[] = ai(n);

ArrayList<Long> a1 = new ArrayList();
ArrayList<Long> a2 = new ArrayList();

  fun(a,0,n/2,0,a1,m);
  fun(a,n/2,n,0,a2,m);

Collections.sort(a2);

long ans=0;

for(int i=0;i<a1.size();i++)
{
    long x = a1.get(i);
    int l=0,r=a2.size();

    while((r-l)>1)
     {
           int mid = (l+r)/2;
           if((x+a2.get(mid))<m)
             l=mid;
           else
               r=mid;
     }
   ans = Math.max(ans,x+a2.get(l));
}
   pn(ans);

   out.flush();
}
static int[] ai(int n)  // it will give in array of size n
{
    int a[] = new int[n];
    for(int i=0;i<n;i++)
        a[i] = ni();
    return a;
}
static long[] al(int n)  // it will give in array of size n
{
    long a[] = new long[n];
    for(int i=0;i<n;i++)
        a[i] = nl();
    return a;
}

static void p(Object o)
{
   out.print(o);
}
static void pn(Object o)
{
    out.println(o);
}
static int abs(int x)
{
    return x>0 ? x : -x;
}
static long gcd(long a,long b)
{
       if(b%a==0)
          return a;
          return gcd(b%a,a);
}
static void subtract_1(char s[]) // it will subtract 1 from the given number.  number should be positive
{
      if(s[0]=='0') // number is zero
          return;
     int n = s.length,i=n-1;
     while(s[i]=='0')
       i--;
     s[i] = (char)((int)(s[i]-'0') + 47);

     for(int j=i+1;j<n;j++)
         s[j]='9';
}
static long pow(long a,long b,long md)
{
    long ans=1;
    while(b>0)
    {
         if(b%2==1)
           ans = (ans*a)%md;
           a = (a*a)%md;
           b = b/2;
    }
   return ans;
}
static long min(long a,long b){

     return a<b ? a : b;
}
static long max(long a,long b){
     return a>b ? a : b;
}
static boolean pal(String s)
{
   int n = s.length(),i1=0,i2=n-1;

     while(i1<i2)
     {
        if(s.charAt(i1)!=s.charAt(i2))
             return false;
             i1++; i2--;
     }
       return true;
}
static String rev(String r)
{
    String s = "";
    int i= r.length()-1;

    while(i>=0)
    {
        s=s+r.charAt(i);
        i--;
    }
       return s;
}
static FastReader sc=new FastReader();

      static int ni(){
                 int x = sc.nextInt();
                 return(x);
        }
      static long nl(){
              long x = sc.nextLong();
              return(x);
         }
      static String n(){
                 String str = sc.next();
                     return(str);
       }
     static String ns(){
                 String str = sc.nextLine();
                   return(str);
      }
     static double nd(){
               double d = sc.nextDouble();
                 return(d);
       }
  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;
        }
    }
}

import java.util.*;
import java.io.*;
public class lp1{
static PrintWriter out = new PrintWriter(System.out);

static void fun(int a[],int is,int in,long sum,ArrayList<Long> arr,int m)
{
        if(is==in)
           {
              arr.add(sum);
              return;
           }
         fun(a,is+1,in,(sum+a[is])%m,arr,m);
         fun(a,is+1,in,sum,arr,m);
}
public static void main(String[] args){

int n = ni();
int m = ni();
int a[] = ai(n);

ArrayList<Long> a1 = new ArrayList();
ArrayList<Long> a2 = new ArrayList();

  fun(a,0,n/2,0,a1,m);
  fun(a,n/2,n,0,a2,m);

Collections.sort(a2);

long ans=0;

for(int i=0;i<a1.size();i++)
{
    long x = a1.get(i);
    int l=0,r=a2.size();

    while((r-l)>1)
     {
           int mid = (l+r)/2;
           if((x+a2.get(mid))<m)
             l=mid;
           else
               r=mid;
     }
   ans = Math.max(ans,x+a2.get(l));
}
   pn(ans);

   out.flush();
}
static int[] ai(int n)  // it will give in array of size n
{
    int a[] = new int[n];
    for(int i=0;i<n;i++)
        a[i] = ni();
    return a;
}
static long[] al(int n)  // it will give in array of size n
{
    long a[] = new long[n];
    for(int i=0;i<n;i++)
        a[i] = nl();
    return a;
}

static void p(Object o)
{
   out.print(o);
}
static void pn(Object o)
{
    out.println(o);
}
static int abs(int x)
{
    return x>0 ? x : -x;
}
static long gcd(long a,long b)
{
       if(b%a==0)
          return a;
          return gcd(b%a,a);
}
static void subtract_1(char s[]) // it will subtract 1 from the given number.  number should be positive
{
      if(s[0]=='0') // number is zero
          return;
     int n = s.length,i=n-1;
     while(s[i]=='0')
       i--;
     s[i] = (char)((int)(s[i]-'0') + 47);

     for(int j=i+1;j<n;j++)
         s[j]='9';
}
static long pow(long a,long b,long md)
{
    long ans=1;
    while(b>0)
    {
         if(b%2==1)
           ans = (ans*a)%md;
           a = (a*a)%md;
           b = b/2;
    }
   return ans;
}
static long min(long a,long b){

     return a<b ? a : b;
}
static long max(long a,long b){
     return a>b ? a : b;
}
static boolean pal(String s)
{
   int n = s.length(),i1=0,i2=n-1;

     while(i1<i2)
     {
        if(s.charAt(i1)!=s.charAt(i2))
             return false;
             i1++; i2--;
     }
       return true;
}
static String rev(String r)
{
    String s = "";
    int i= r.length()-1;

    while(i>=0)
    {
        s=s+r.charAt(i);
        i--;
    }
       return s;
}
static FastReader sc=new FastReader();

      static int ni(){
                 int x = sc.nextInt();
                 return(x);
        }
      static long nl(){
              long x = sc.nextLong();
              return(x);
         }
      static String n(){
                 String str = sc.next();
                     return(str);
       }
     static String ns(){
                 String str = sc.nextLine();
                   return(str);
      }
     static double nd(){
               double d = sc.nextDouble();
                 return(d);
       }
  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;
        }
    }
}

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

public class E_MaximumSubsequence {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader inp = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        Solver solver = new Solver();
        solver.solve(inp, out);
        out.close();
    }

    static class Solver {
        private ArrayList<Integer> remainders(ArrayList<Integer> a, int m) {
            int maxMask = 1 << a.size();
            ArrayList<Integer> res = new ArrayList<>();
            for (int mask = 0; mask < maxMask; mask++) {
                int sum = 0;
                for (int j = 0; j < a.size(); j++) {
                    if ((mask & (1 << j)) != 0) {
                        sum = (sum + a.get(j)) % m;
                    }
                }
                res.add(sum);
            }
            return res;
        }

        private int binarySearch(ArrayList<Integer> a, int right) {
            int l = 0, r = a.size() - 1;
            while (l + 1 < r) {
                int mid = l + ((r - l) >> 1);
                if (a.get(mid) <= right) l = mid;
                else if (a.get(mid) > right) r = mid - 1;
            }
            if (a.get(r) <= right) return a.get(r);
            else if (a.get(l) <= right) return a.get(l);
            return -1;
        }

        private void solve(InputReader inp, PrintWriter out) {
            int n = inp.nextInt(), m = inp.nextInt(), right = (n - 1) >> 1;
            ArrayList<Integer> a = new ArrayList<>();
            ArrayList<Integer> b = new ArrayList<>();
            for (int i = 0; i < n; i++) {
                if (i <= right) a.add(inp.nextInt());
                else b.add(inp.nextInt());
            }

            ArrayList<Integer> r1 = remainders(a, m);
            ArrayList<Integer> r2 = remainders(b, m);
            Collections.sort(r2);
            int res = 0;
            for (int i: r1) {
                int add = binarySearch(r2, m - i - 1);
                if (add == -1) continue;
                res = Math.max(res, i + add);
            }
            out.print(res);
        }
    }

    static class InputReader {
        BufferedReader reader;
        StringTokenizer tokenizer;

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

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

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

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

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.TreeSet;
import java.io.InputStream;

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

    static class TaskE {
        public void solve(int testNumber, InputReader in, OutputWriter out) {
            int n = in.readInt(); // 1 <= 35
            int mod = in.readInt(); //
            int[] ar = new int[n];
            for (int i = 0; i < n; i++) {
                ar[i] = in.readInt() % mod;
            }
            if (n == 1) {
                out.printLine(ar[0]);
                return;
            }
            int[] tmp = new int[200000];
            TreeSet<Integer> left = new TreeSet<>();
            TreeSet<Integer> right = new TreeSet<>();
            for (int i = 0; i < n / 2; i++) {
                int idx = 0;
                for (Integer sum : left) {
                    tmp[idx] = (sum + ar[i]) % mod;
                    idx++;
                }
                left.add(ar[i]);
                for (int j = 0; j < idx; j++) {
                    left.add(tmp[j]);
                }
            }
            for (int i = n / 2; i < n; i++) {
                int idx = 0;
                for (Integer sum : right) {
                    tmp[idx] = (sum + ar[i]) % mod;
                    idx++;
                }
                right.add(ar[i]);
                for (int j = 0; j < idx; j++) {
                    right.add(tmp[j]);
                }
            }
            int res = Math.max(left.last(), right.last());
            for (Integer count : left) {
                Integer dev = right.floor(mod - count - 1);
                if (dev == null) dev = 0;
                int curMax = Math.max(count + dev, count);
                if (curMax > res) res = curMax;
            }
            out.printLine(res);
        }

    }

    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private InputReader.SpaceCharFilter filter;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars == -1) {
                throw new InputMismatchException();
            }
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (numChars <= 0) {
                    return -1;
                }
            }
            return buf[curChar++];
        }

        public int readInt() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9') {
                    throw new InputMismatchException();
                }
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public boolean isSpaceChar(int c) {
            if (filter != null) {
                return filter.isSpaceChar(c);
            }
            return isWhitespace(c);
        }

        public static boolean isWhitespace(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);

        }

    }

    static class OutputWriter {
        private final PrintWriter writer;

        public OutputWriter(OutputStream outputStream) {
            writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
        }

        public OutputWriter(Writer writer) {
            this.writer = new PrintWriter(writer);
        }

        public void close() {
            writer.close();
        }

        public void printLine(int i) {
            writer.println(i);
        }

    }
}

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;

public class Problem32E {
	public static void main(String[] args) throws Exception {
		BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
		PrintWriter writer = new PrintWriter(System.out);

		StringTokenizer info = new StringTokenizer(reader.readLine());

		int n = Integer.parseInt(info.nextToken());
		long m = Long.parseLong(info.nextToken());

		if (n == 1) {
			writer.println(Integer.parseInt(reader.readLine()) % m);
			reader.close();
			writer.close();
			return;
		}

		int firstHalf = n / 2;
		int secondHalf = n - firstHalf;

		StringTokenizer tokenizer = new StringTokenizer(reader.readLine());
		long[] first = new long[firstHalf];
		long[] second = new long[secondHalf];
		for (int i = 0; i < first.length; i++) {
			first[i] = Long.parseLong(tokenizer.nextToken()) % m;
		}
		for (int i = 0; i < second.length; i++) {
			second[i] = Long.parseLong(tokenizer.nextToken()) % m;
		}
		long[] firstSums = getSums(first, m);
		long[] secondSums = getSums(second, m);
		Arrays.sort(firstSums);
		Arrays.sort(secondSums);
		int j = secondSums.length - 1;
		long answer = 0;
		bigLoop: for (int i = 0; i < firstSums.length; i++) {
			while (firstSums[i] + secondSums[j] >= m) {
				j--;
				if (j < 0) {
					break bigLoop;
				}
			}
			answer = Math.max(answer, firstSums[i] + secondSums[j]);
		}
		writer.println(answer);
		reader.close();
		writer.close();
	}
	public static long[] getSums(long[] array, long m) {
		long[] sums = new long[1 << array.length];
		for (int i = 0; i < sums.length; i++) {
			long sum = 0;
			for (int j = 0; j < array.length; j++) {
				if (((i >>> j) & 0b1) == 1) {
					sum = (sum + array[j]) % m;
				}
			}
			sums[i] = sum;
		}
		return sums;
	}
}

import java.util.*;
import java.io.*;
import java.math.*;
public class Main
{
    static class Reader
    {
        private InputStream mIs;private byte[] buf = new byte[1024];private int curChar,numChars;public Reader() { this(System.in); }public Reader(InputStream is) { mIs = is;}
        public int read() {if (numChars == -1) throw new InputMismatchException();if (curChar >= numChars) {curChar = 0;try { numChars = mIs.read(buf);} catch (IOException e) { throw new InputMismatchException();}if (numChars <= 0) return -1; }return buf[curChar++];}
        public String nextLine(){int c = read();while (isSpaceChar(c)) c = read();StringBuilder res = new StringBuilder();do {res.appendCodePoint(c);c = read();}while (!isEndOfLine(c));return res.toString() ;}
        public String s(){int c = read();while (isSpaceChar(c)) c = read();StringBuilder res = new StringBuilder();do {res.appendCodePoint(c);c = read();}while (!isSpaceChar(c));return res.toString();}
        public long l(){int c = read();while (isSpaceChar(c)) c = read();int sgn = 1;if (c == '-') { sgn = -1 ; c = read() ; }long res = 0; do{ if (c < '0' || c > '9') throw new InputMismatchException();res *= 10 ; res += c - '0' ; c = read();}while(!isSpaceChar(c));return res * sgn;}
        public int i(){int c = read() ;while (isSpaceChar(c)) c = read();int sgn = 1;if (c == '-') { sgn = -1 ; c = read() ; }int res = 0;do{if (c < '0' || c > '9') throw new InputMismatchException();res *= 10 ; res += c - '0' ; c = read() ;}while(!isSpaceChar(c));return res * sgn;}
        public double d() throws IOException {return Double.parseDouble(s()) ;}
        public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; }
        public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; }
        public int[] arr(int n){int[] ret = new int[n];for (int i = 0; i < n; i++) {ret[i] = i();}return ret;}
    }

           //       |----|       /\      |    |   -----   |
           //       |   /       /  \     |    |     |     |
           //       |--/       /----\    |----|     |     |
           //       |   \     /      \   |    |     |     |
           //       |    \   /        \  |    |   -----   -------

    public static void main(String[] args)throws IOException
    {
        Reader sc=new Reader();
        PrintWriter out=new PrintWriter(System.out);
        int n=sc.i();
        int m=sc.i();
        long arr[]=new long[n];
        for(int i=0;i<n;i++)arr[i]=sc.l();
        TreeSet<Long> ts1=new TreeSet<>();
        TreeSet<Long> ts2=new TreeSet<>();
        long max=0;
        for(int bit=1;bit<(1<<(n/2));bit++)
        {
            long sum=0;
            for(int i=0;i<n/2;i++)
            {
                if((bit&(1<<i))>0)
                sum+=arr[i];
            }
            ts1.add(sum%m);
            max=Math.max(max,sum%m);
        }
        for(int bit=1;bit<(1<<(n-n/2));bit++)
        {
            long sum=0;
            for(int i=n/2;i<n;i++)
            {
                if((bit&(1<<(i-n/2)))>0)
                sum+=arr[i];
            }
            ts2.add(sum%m);
            max=Math.max(max,sum%m);
        }
        for(long i:ts1)
        {
            long val1=0,val2=0;
            if(ts2.lower(m-i)!=null)
            val1=ts2.lower(m-i);
            max=Math.max((i+val1)%m,max);
            max=Math.max(max,(i+ts2.last())%m);
        }
        out.println(max);
        out.flush();
    }
}

import java.io.*;
import java.util.Arrays;
import java.util.StringTokenizer;

public class MaximumSubsequence {
    public static void main(String[] args) throws Exception{
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter writer = new PrintWriter(System.out);
//        BufferedReader reader = new BufferedReader(new FileReader("subsequence.in"));
//        PrintWriter writer = new PrintWriter(new FileWriter("subsequence.out"));

        StringTokenizer tokenizer = new StringTokenizer(reader.readLine());
        int n = Integer.parseInt(tokenizer.nextToken());
        int m = Integer.parseInt(tokenizer.nextToken());

        long[] array1 = new long[n/2];
        long[] array2 = new long[n-array1.length];
        tokenizer = new StringTokenizer(reader.readLine());
        for (int i = 0; i < n/2; i++){
            long a = Long.parseLong(tokenizer.nextToken());
            array1[i] = a % m;
        }
        for (int i = 0; i < n-n/2; i++){
            long a = Long.parseLong(tokenizer.nextToken());
            array2[i] = a % m;
        }
        long[] firstSums = toSums(array1, m);
        long[] secondSums = toSums(array2, m);
        Arrays.sort(firstSums);
        Arrays.sort(secondSums);

        int i = 0;
        int j = secondSums.length-1;
        long greatestSum = 0;

        while (i < firstSums.length && j >= 0){
            long x = firstSums[i] + secondSums[j];
            if (x >= m){
                j--;
                greatestSum = Math.max(greatestSum, x % m);
            } else if (x <= m-2){
                i++;
                greatestSum = Math.max(greatestSum, x % m);
            } else{
                writer.println(m-1);
                reader.close();
                writer.close();
                break;
            }
        }
        writer.println(greatestSum);
        reader.close();
        writer.close();
    }

    public static long[] toSums(long[] array, int m) {
        int n = array.length;
        long[] ret = new long[1 << n];
        for (int i = 0; i < 1 << n; i++) {
            long sum = 0;
            for (int j = 0; j < n; j++) {
                if (((i >> j) & 0b1) == 1) {
                    sum += array[j];
                }
            }
            ret[i] = sum % m;
        }
        return ret;
    }
}

/**
 * ******* Created  on 8/4/20 4:52 AM*******
 */

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

public class E888 implements Runnable {

    private static final int MAX = (int) (1E5 + 5);
    private static final int MOD = (int) (1E9 + 7);
    private static final long Inf = (long) (1E14 + 10);
    private static final double eps = (double) (1E-9);

    private void solve() throws IOException {
        int n = reader.nextInt();
        int m = reader.nextInt();
        int st = (n+1)/2;
        long[] a = new long[50];
        for(int i=0;i<n;i++){
            a[i] =reader.nextInt();
        }
        TreeSet<Long> set = new TreeSet<>();
        for(int i=0;i<(1<<st);i++){
            long cur =0;
            for(int j=0;j<st;j++)
                if((i&(1<<j)) !=0)
                    cur = (cur+a[j])%m;
            set.add(cur);
        }

        int st2 = n-st;
        long ans =0;
        for(int i=0;i<(1<<st2);i++){
            long cur =0;
            for(int j=0;j<st2;j++)
                if((i&(1<<j))!=0)
                    cur =(cur+ a[j+st] )%m;
            long val = (m-1- cur)%m;
            Long val2 = set.floor(val);
            if(val2 == null)
                val2 = Long.valueOf(0);
            ans = Math.max(ans, val2 + cur );
        }
        writer.println(ans);
    }

    public static void main(String[] args) throws IOException {
        try (Input reader = new StandardInput(); PrintWriter writer = new PrintWriter(System.out)) {
            new E888().run();
        }
    }

    StandardInput reader;
    PrintWriter writer;

    @Override
    public void run() {
        try {
            reader = new StandardInput();
            writer = new PrintWriter(System.out);
            solve();
            reader.close();
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    interface Input extends Closeable {
        String next() throws IOException;

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

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

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

        default int[] readIntArray() throws IOException {
            return readIntArray(nextInt());
        }

        default int[] readIntArray(int size) throws IOException {
            int[] array = new int[size];
            for (int i = 0; i < array.length; i++) {
                array[i] = nextInt();
            }
            return array;
        }

        default long[] readLongArray(int size) throws IOException {
            long[] array = new long[size];
            for (int i = 0; i < array.length; i++) {
                array[i] = nextLong();
            }
            return array;
        }
    }

    private static class StandardInput implements Input {
        private final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        private StringTokenizer stringTokenizer;

        @Override
        public void close() throws IOException {
            reader.close();
        }

        @Override
        public String next() throws IOException {
            if (stringTokenizer == null || !stringTokenizer.hasMoreTokens()) {
                stringTokenizer = new StringTokenizer(reader.readLine());
            }
            return stringTokenizer.nextToken();
        }
    }
}

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class P888E {
    private static class HpReader {
        private BufferedReader in;
        private String containingDirPath;

        public HpReader(String dir, String inFile, String outFile) {
            initAndRedirectInOut(dir, inFile, outFile);
        }

        private static int ivl(String val) {
            return Integer.parseInt(val);
        }

        private void initAndRedirectInOut(String dir, String inFile, String outFile) {
            if (dir != null) {
                try {
                    containingDirPath = dir.endsWith(File.separator) ? dir : dir + File.separator;
                    if (isDebug && inFile != null) System.setIn(new FileInputStream(new File(containingDirPath + inFile)));
                    if (isDebug && outFile != null) System.setOut(new PrintStream(new File(containingDirPath + outFile)));
                } catch (FileNotFoundException e) {
                    // Do nothing, stdin & stdout are not redirected
                }
            }
            in = new BufferedReader(new InputStreamReader(System.in));
            out = new PrintWriter(System.out);
        }

        private String nextSingleStr() throws IOException {
            return in.readLine();
        }

        private String[] nextLineStr() throws IOException {
            return nextLineStr(0);
        }

        private String[] nextLineStr(int offset) throws IOException {
            String[] inp = nextSingleStr().split(" ");
            String[] rs = new String[offset + inp.length];
            System.arraycopy(inp, 0, rs, offset, inp.length);
            return rs;
        }

        private int nextSingleInt() throws IOException {
            return ivl(in.readLine());
        }

        private int[] nextLineInt() throws IOException {
            return nextLineInt(0);
        }

        private int[] nextLineInt(int offset) throws IOException {
            String[] inp = nextLineStr();
            int[] rs = new int[offset + inp.length];
            for (int i = 0; i < inp.length; i++) rs[offset + i] = ivl(inp[i]);
            return rs;
        }

        private int[][] nextMatInt(int lineCount) throws IOException {
            return nextMatInt(lineCount, 0, 0);
        }

        private int[][] nextMatInt(int lineCount, int rowOffset, int colOffset) throws IOException {
            int[][] rs = new int[rowOffset + lineCount][];
            for (int i = rowOffset; i < rs.length; i++) rs[i] = nextLineInt(colOffset);
            return rs;
        }
    }

    private static class HpHelper {
        private static final String LOCAL_DEBUG_FLAG = "COM_PROG_DEBUG";

        private static boolean isDebug() {
            try {
                return Boolean.parseBoolean(System.getenv(HpHelper.LOCAL_DEBUG_FLAG));
            } catch (Exception e) {
                return false;
            }
        }

        private static String createDelimiter(String delimiter) {
            return delimiter == null ? " " : delimiter;
        }

        private static void println(int[] data, String delimiter) {
            delimiter = createDelimiter(delimiter);
            for (int t : data) out.print(t + delimiter);
            out.println();
        }

        private static void println(long[] data, String delimiter) {
            delimiter = createDelimiter(delimiter);
            for (long t : data) out.print(t + delimiter);
            out.println();
        }

        private static <T> void println(T[] data, String delimiter) {
            delimiter = createDelimiter(delimiter);
            for (T t : data) {
                if (t instanceof int[]) {
                    println((int[]) t, delimiter);
                } else if (t instanceof long[]) {
                    println((long[]) t, delimiter);
                } else if (t instanceof Object[]) {
                    println((Object[]) t, delimiter);
                } else {
                    out.print(t + delimiter);
                }
            }
            out.println();
        }
    }

    private static boolean isDebug = HpHelper.isDebug();
    private static HpReader in = new HpReader("/Users/apple/Work/WorkSpaces/CompetitiveProg/", "in.txt", null);
    private static PrintWriter out;

    private static void calRem(int[] data, int lv, List<Integer> target, int carried, int mod) {
        if (lv >= data.length) {
            target.add(carried);
            return;
        }

        calRem(data, lv + 1, target, carried % mod, mod);
        calRem(data, lv + 1, target, (carried % mod + data[lv] % mod) % mod, mod);
    }

    public static void main(String[] args) throws IOException {
        int[] inp = in.nextLineInt();
        int n = inp[0], m = inp[1], rs = 0;
        int[] data = in.nextLineInt();
        int[] dt1 = Arrays.copyOfRange(data, 0, n / 2), dt2 = Arrays.copyOfRange(data, n / 2, n);
        List<Integer> l1 = new ArrayList<>(1 << dt1.length), l2 = new ArrayList<>(1 << dt2.length);

        calRem(dt1, 0, l1, 0, m);
        calRem(dt2, 0, l2, 0, m);

        Collections.sort(l2);
        for (int i : l1) {
            int r = m - 1 - i;
            int pos = Collections.binarySearch(l2, r), toAdd = -1;
            if (pos < 0) {
                pos = -pos - 1;
                if (pos >= l2.size()) {
                    pos = l2.size() - 1;
                    toAdd = l2.get(pos);
                } else {
                    if (pos == 0) {
                        toAdd = 0;
                    } else {
                        toAdd = l2.get(pos - 1);
                    }
                }
            } else {
                toAdd = l2.get(pos);
            }
            rs = Math.max(rs, (i + toAdd) % m);
        }
        out.println(rs);

        out.flush();
    }
}

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

public class Main{
class Node {
    int id;
    long mask;
    public Node(int id,long mask){
        this.id=id;
        this.mask=mask;

    }
    @Override
    public boolean equals(Object o){
        Node c=(Node)o;
        return id==c.id && mask==c.mask;

    }
}
    void solve() {
        int n=ni();
        M=nl();
        a=new long[n];
        for(int i=0;i<n;i++) a[i]=nl()%M;
        TreeSet<Long> ts1=new TreeSet<>();
        TreeSet<Long> ts2=new TreeSet<>();
        long ans=0;
        for(int mask=0;mask<(1<<Math.min(n,18));mask++){
            long sm=0;
            for(int j=0;j<Math.min(n,18);j++){
                if((mask&(1<<j))>0){
                    sm+=a[j];
                    sm%=M;
                }
            }
            ans=Math.max(ans,sm);
            ts1.add(sm);
        }
        for(int mask=0;n>18 && mask<1<<(n-18);mask++){
            long sm=0;
            for(int j=0;j<n-18;j++){
                if((mask&(1<<j))>0){
                    sm+=a[j+18];
                    sm%=M;
                }
            }
            ans=Math.max(ans,sm);
            ts2.add(sm);
        }
        for(long v : ts1){
            if(ts2.lower(M-v)!=null) {
                long v2=ts2.lower(M-v);
                ans=Math.max(ans,v+v2);
            }
        }
        pw.println(ans);

    }
    long a[];

    long M=(long)1e9+7;
    InputStream is;
    PrintWriter pw;
    String INPUT = "";
    void run() throws Exception {
        is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
        pw = new PrintWriter(System.out);
        long s = System.currentTimeMillis();
        solve();
        pw.flush();
        if(!INPUT.isEmpty())tr(System.currentTimeMillis()-s+"ms");
    }

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

    private byte[] inbuf = new byte[1024];
    public int lenbuf = 0, ptrbuf = 0;

    private int readByte() {
        if(lenbuf == -1)throw new InputMismatchException();
        if(ptrbuf >= lenbuf){
            ptrbuf = 0;
            try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
            if(lenbuf <= 0)return -1;
        }
        return inbuf[ptrbuf++];
    }

    private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
    private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }

    private double nd() { return Double.parseDouble(ns()); }
    private char nc() { return (char)skip(); }

    private String ns() {
        int b = skip();
        StringBuilder sb = new StringBuilder();
        while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
            sb.appendCodePoint(b);
            b = readByte();
        }
        return sb.toString();
    }

    private char[] ns(int n) {
        char[] buf = new char[n];
        int b = skip(), p = 0;
        while(p < n && !(isSpaceChar(b))){
            buf[p++] = (char)b;
            b = readByte();
        }
        return n == p ? buf : Arrays.copyOf(buf, p);
    }

    private char[][] nm(int n, int m) {
        char[][] map = new char[n][];
        for(int i = 0;i < n;i++)map[i] = ns(m);
        return map;
    }

    private int[] na(int n) {
        int[] a = new int[n];
        for(int i = 0;i < n;i++)a[i] = ni();
        return a;
    }

    private int ni() {
        int num = 0, b;
        boolean minus = false;
        while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
        if(b == '-'){
            minus = true;
            b = readByte();
        }

        while(true){
            if(b >= '0' && b <= '9'){
                num = num * 10 + (b - '0');
            }else{
                return minus ? -num : num;
            }
            b = readByte();
        }
    }

    private long nl() {
        long num = 0;
        int b;
        boolean minus = false;
        while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
        if(b == '-'){
            minus = true;
            b = readByte();
        }

        while(true){
            if(b >= '0' && b <= '9'){
                num = num * 10 + (b - '0');
            }else{
                return minus ? -num : num;
            }
            b = readByte();
        }
    }

    private void tr(Object... o) { if(INPUT.length() > 0)System.out.println(Arrays.deepToString(o)); }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Set;
import java.util.NavigableSet;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.TreeSet;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author svilen.marchev@gmail.com
 */
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);
    TaskE solver = new TaskE();
    solver.solve(1, in, out);
    out.close();
  }

  static class TaskE {
    int n;
    int m;
    int[] a;

    long buildSum(int b, int size, int offset) {
      long sum = 0;
      for (int i = 0; i < size; ++i) {
        if (((b >>> i) & 1) == 1) {
          sum = (sum + a[offset + i]) % m;
        }
      }
      return sum;
    }

    public void solve(int testNumber, InputReader in, PrintWriter out) {
      n = in.readInt();
      m = in.readInt();
      a = new int[n];
      for (int i = 0; i < n; ++i) {
        a[i] = in.readInt() % m;
      }

      if (n == 1) {
        out.println(a[0]);
        return;
      }

      int setASz = n / 2;
      long setAMax = 0;
      NavigableSet<Long> setA = new TreeSet<>();
      for (int b = 0; b < (1 << setASz); ++b) {
        long sum = buildSum(b, setASz, 0);
        setA.add(sum);
        setAMax = Math.max(setAMax, sum);
      }

      int setBSz = n - setASz;
      long ans = 0;
      for (int b = 0; b < (1 << setBSz); ++b) {
        long sum = buildSum(b, setBSz, setASz);

        long greatestSmallerNum = setA.lower(m - sum);
        ans = Math.max(ans, (sum + greatestSmallerNum) % m);

        ans = Math.max(ans, (sum + setAMax) % m);
      }
      out.println(ans);
    }

  }

  static class InputReader {
    private InputStream stream;
    private byte[] buf = new byte[1024];
    private int curChar;
    private int numChars;
    private InputReader.SpaceCharFilter filter;

    public InputReader(InputStream stream) {
      this.stream = stream;
    }

    public int read() {
      if (numChars == -1) {
        throw new InputMismatchException();
      }
      if (curChar >= numChars) {
        curChar = 0;
        try {
          numChars = stream.read(buf);
        } catch (IOException e) {
          throw new InputMismatchException();
        }
        if (numChars <= 0) {
          return -1;
        }
      }
      return buf[curChar++];
    }

    public int readInt() {
      int c = read();
      while (isSpaceChar(c)) {
        c = read();
      }
      int sgn = 1;
      if (c == '-') {
        sgn = -1;
        c = read();
      }
      int res = 0;
      do {
        if (c < '0' || c > '9') {
          throw new InputMismatchException();
        }
        res *= 10;
        res += c - '0';
        c = read();
      } while (!isSpaceChar(c));
      return res * sgn;
    }

    public boolean isSpaceChar(int c) {
      if (filter != null) {
        return filter.isSpaceChar(c);
      }
      return isWhitespace(c);
    }

    public static boolean isWhitespace(int c) {
      return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
    }

    public interface SpaceCharFilter {
      public boolean isSpaceChar(int ch);

    }

  }
}

import java.util.*;
import java.io.*;
import java.lang.*;
public class E32E {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner sc =new Scanner(System.in);
		int n =sc.nextInt();
		int m =sc.nextInt();
		int f=n/2,l=n-f;
		long a[] =new long[f];
		long b[] =new long[l];
		for(int i=0;i<f;i++){
			a[i]=sc.nextInt();
		}
		for(int i=0;i<l;i++){
			b[i]=sc.nextInt();
		}
		int sf[] =new int[1<<f];
		int sl[] =new int[1<<l];
		for(int i=1;i<(1<<f);i++){
			for(int j=0;j<f;j++){
				if((i&(1<<j))!=0){
					sf[i]=(int)(sf[i]+a[j])%m;
				}
			}
		}
		Arrays.sort(sf);
		for(int i=1;i<(1<<l);i++){
			for(int j=0;j<l;j++){
				if((i&(1<<j))>0){
					sl[i]=(int)(sl[i]+b[j])%m;
				}
			}
		}
		Arrays.sort(sl);
		int max =Integer.MIN_VALUE;
		for(int i=0;i<sf.length;i++){
			int find =(int)(m-1-sf[i]);
			int in=Arrays.binarySearch(sl,find);
			if(in<-1){
				in =-in-2;
				int temp=sl[in]+sf[i];
				if(temp>max){
					max=temp;
				}
			}
			if(in>=0){
				max=m-1;
				break;
			}
		}
		if(max!=m-1){
		for(int i=0;i<sl.length;i++){
			int find =(int)(m-1-sl[i]);
			int in=Arrays.binarySearch(sf,find);
			if(in<-1){
				in =-in-2;
				int temp=sf[in]+sl[i];
				if(temp>max){
					max=temp;
				}
			}
			if(in>=0){
				max=m-1;
				break;
			}
		}
		}
		System.out.println(max);
	}

}

/*
 * DA-IICT
 * Author: Jugal Kalal
 */
import java.util.*;
import java.io.*;
import java.math.*;
import java.text.DecimalFormat;
public class Hackerrank{
	static long mod=(long)Math.pow(10,9)+7;
	public static void main(String args[]) {
        new Thread(null, new Runnable() {
            public void run() {
                try{
                    solve();
                    w.close();
                }
                catch(Exception e){
                    e.printStackTrace();
                }
            }
        }, "1", 1 << 26).start();
	}
	static InputReader in;
    static PrintWriter w;
    static void solve(){
        in = new InputReader(System.in);
        w = new PrintWriter(System.out);
        int n=in.nextInt();
        long m=in.nextLong();
        long arr[]=in.nextLongArray(n);
        long ans[]=new long[n+1];
        long max=0;
        for(int i=1;i<=n;i++) {
        		long temp=0;
        		for(int j=0;j<=i-1;j++) {
        			if((arr[i-1]+ans[j])%m>temp) {
        				temp=(arr[i-1]+ans[j])%m;
        			}
        		}
        		ans[i]=temp;
        		max=Math.max(max,ans[i]);
        }
        w.println(max);
    }
    static boolean check(int k,String str,char c) {
    		int count=0;
    		for(int i=0;i<k;i++) {
    			if(str.charAt(i)==c) {
    				count++;
    			}
    		}
    		if(count==0) {
    			return false;
    		}
    		for(int i=k;i<str.length();i++) {
    			if(str.charAt(i-k)==c) {
    				count--;
    			}
    			if(str.charAt(i)==c) {
    				count++;
    			}
    			if(count==0) {
    				return false;
    			}
    		}
    		return true;
    }
	static class Pair{
			int parent;
			int type;
			public Pair(int parent,int type) {
				this.parent=parent;
				this.type=type;
			}
	}
	static class Triple{
			int f;
			int s;
			int t;
			public Triple(int f,int s,int t) {
				this.f=f;
				this.s=s;
				this.t=t;
			}
	}
    static int parent[];
    static TreeMap<Integer,ArrayList<Integer>> levels=new TreeMap<>(Collections.reverseOrder());
    static void bfs(int s,int n) {
    		boolean vis[]=new boolean[n];
    		Queue<Integer> queue=new LinkedList<>();
    		Queue<Integer> lev=new LinkedList<>();
    		queue.add(s);
    		vis[s]=true;
    		lev.add(0);
    		parent[0]=-1;
    		while(!queue.isEmpty()) {
    			int top=queue.poll();
    			int l=lev.poll();
    			ArrayList<Integer> temp;
    			if(levels.containsKey(l)) {
    				temp=levels.get(l);
    			}else {
    				temp=new ArrayList<>();
    			}
    			temp.add(top);
    			levels.put(l,temp);
    			for(int v:adj[top]) {
    				if(!vis[v]) {
    					vis[v]=true;
    					lev.add(l+1);
    					queue.add(v);
    				}
    			}
    		}
    }
    static ArrayList<Integer> adj[]; //Adjacency Lists
    static int V;   // No. of vertices
    // Constructor
    static void Graph(int v){
        V = v;
        adj = new ArrayList[v];
        for (int i=0; i<v; ++i){
        		adj[i] = new ArrayList();
        }
    }

    // Function to add an edge into the graph
    static void addEdge(int u,int v){
		adj[u].add(v);
		adj[v].add(u);
    }
//    static long[] isHamiltonian_path(int n){
//    	boolean dp[][]=new boolean[n][1<<n];
//    	long ans[]=new long[n];
//    	long sum[]=new long[n];
//    	for(int i=0;i<n;i++){
//    		dp[i][1<<i]=true;
//    		ans[i]=0;
//    		sum[i]=i+1;
//    	}
//    	for(int mask=0;mask<(1<<n);mask++){
//    		int s=0;
//    		int count=0,temp=mask;
//    		while(temp>0){
//    			s+=1+Math.log(temp&(-temp))/Math.log(2);
//    			temp=temp&(temp-1);
//    			count++;
//    		}
//    		for(int j=0;j<n;j++){
//    			if((mask&(1<<j))>0){
//    				for(int k=0;k<n;k++){
//    					if(j!=k&&(mask&(1<<k))>0&&adj[j][k]&&dp[k][mask^(1<<j)]){
//    						dp[j][mask]=true;
//    						ans[j]=Math.max(ans[j],count-1);
//    						if(ans[j]==count-1){
//    							sum[j]=Math.max(sum[j], s);
//    						}
//    					}
//    				}
//    			}
//    		}
//    	}
//    	return sum;
//    }
//    static void bfs(int s,int n){
//    	boolean visited[]=new boolean[n];
//    	LinkedList<Integer> queue=new LinkedList<Integer>();
//    	queue.add(s);
//    	visited[s]=true;
//    	while(!queue.isEmpty()){
//    		int num=queue.pop();
////    		System.out.println(ans.toString());
//    		for(int i=0;i<adj[num].size();i++){
//    			if(!visited[adj[num].get(i)]){
//    				visited[adj[num].get(i)]=true;
//    				queue.add(adj[num].get(i));
//    			}
//    		}
//    	}
//    }
    static long gcd(long a,long b){
		if(a==0){
			return b;
		}
		return gcd(b%a,a);
	}
    static long power(long base, long exponent, long modulus){
	    long result = 1L;
	    while (exponent > 0) {
	        if (exponent % 2L == 1L)
	            result = (result * base) % modulus;
	        exponent = exponent >> 1;
	        base = (base * base) % modulus;
	    }
	    return result;
	}
    static HashMap<Long,Long> primeFactors(long n){
        HashMap<Long,Long> ans=new HashMap<Long,Long>();
    	// Print the number of 2s that divide n
        while (n%2L==0L)
        {
            if(ans.containsKey(2L)){
            	ans.put(2L,ans.get(2L)+1L);
            }else{
            	ans.put(2L,1L);
            }
            n /= 2L;
        }

        // n must be odd at this point.  So we can
        // skip one element (Note i = i +2)
        for (long i = 3; i <= Math.sqrt(n); i+= 2L)
        {
            // While i divides n, print i and divide n
            while (n%i == 0)
            {
            	if(ans.containsKey(i)){
                	ans.put(i,ans.get(i)+1L);
                }else{
                	ans.put(i,1L);
                }
                n /= i;
            }
        }

        // This condition is to handle the case whien
        // n is a prime number greater than 2
        if (n > 2)
            ans.put(n,1L);
        return ans;
    }
////for marking all prime numbers greater than 1 and less than equal to N
	static boolean[] sieve(int N) {
		 boolean isPrime[]=new boolean[N+1];
		 isPrime[0] = true;
		 isPrime[1] = true;
		 for(int i = 2; i * i <= N; ++i) {
		      if(isPrime[i] == false) {//Mark all the multiples of i as composite numbers
		          for(int j = i * i; j <= N ;j += i)
		              isPrime[j] = true;
		     }
		 }
		 return isPrime;
	}
//  //if  str2 (pattern) is subsequence of str1 (Text) or not
//	static boolean function(String str1,String str2){
//	     str2 = str2.replace("", ".*");  //returns .*a.*n.*n.*a.
//	     return (str1.matches(str2));  // returns true
//	}
    static int Arr[];
    static long size[];
  //modified initialize function:
    static void initialize(int N){
    	Arr=new int[N];
    	size=new long[N];
        for(int i = 0;i<N;i++){
        	Arr[ i ] = i ;
        	size[ i ] = 1;
        }
    }
    static boolean find(int A,int B){
        if( root(A)==root(B) )       //if A and B have same root,means they are connected.
        return true;
        else
        return false;
    }
 // modified root function.
    static void weighted_union(int A,int B,int n){
        int root_A = root(A);
        int root_B = root(B);
        if(size[root_A] < size[root_B ]){
        	Arr[ root_A ] = Arr[root_B];
        	size[root_B] += size[root_A];
        }
        else{
        	Arr[ root_B ] = Arr[root_A];
        	size[root_A] += size[root_B];
        }
    }
    static int root (int i){
        while(Arr[ i ] != i){
            Arr[ i ] = Arr[ Arr[ i ] ] ;
            i = Arr[ i ];
        }
        return i;
    }

	static boolean isPrime(long n) {
		if(n < 2L) return false;
		if(n == 2L || n == 3L) return true;
		if(n%2L == 0 || n%3L == 0) return false;
		long sqrtN = (long)Math.sqrt(n)+1L;
		for(long i = 6L; i <= sqrtN; i += 6L) {
			if(n%(i-1) == 0 || n%(i+1) == 0) return false;
		}
		return true;
	}
//	static HashMap<Integer,Integer> level;;
//	static HashMap<Integer,Integer> parent;
	static int maxlevel=0;

//	static boolean T[][][];
//	static void subsetSum(int input[], int total, int count) {
//        T = new boolean[input.length + 1][total + 1][count+1];
//        for (int i = 0; i <= input.length; i++) {
//        	T[i][0][0] = true;
//        	for(int j = 1; j<=count; j++){
//        		T[i][0][j] = false;
//        	}
//        }
//        int sum[]=new int[input.length+1];
//        for(int i=1;i<=input.length;i++){
//            sum[i]=sum[i-1]+input[i-1];
//        }
//        for (int i = 1; i <= input.length; i++) {
//            for (int j = 1; j <= (int)Math.min(total,sum[i]); j++) {
//            	for (int k = 1; k <= (int)Math.min(i,count); k++){
//            		 if (j >= input[i - 1]) {//Exclude and Include
//                         T[i][j][k] = T[i - 1][j][k] || T[i - 1][j - input[i - 1]][k-1];
//                     } else {
//                         T[i][j][k] = T[i-1][j][k];
//                     }
//            	}
//            }
//        }
//    }
//	static <K,V extends Comparable<? super V>>
//	SortedSet<Map.Entry<K,V>> entriesSortedByValues(Map<K,V> map) {
//	    SortedSet<Map.Entry<K,V>> sortedEntries = new TreeSet<Map.Entry<K,V>>(
//	        new Comparator<Map.Entry<K,V>>() {
//	            @Override public int compare(Map.Entry<K,V> e1, Map.Entry<K,V> e2) {
//	                int res = e2.getValue().compareTo(e1.getValue());
//	                return res != 0 ? res : 1;
//	            }
//	        }
//	    );
//	    sortedEntries.addAll(map.entrySet());
//	    return sortedEntries;
//	}

	//minimum prime factor of all the numbers less than n
    static int minPrime[];
	static void minimumPrime(int n){
		minPrime=new int[n+1];
		minPrime[1]=1;
        for (int i = 2; i * i <= n; ++i) {
            if (minPrime[i] == 0) {         //If i is prime
                for (int j = i * i; j <= n; j += i) {
                    if (minPrime[j] == 0) {
                        minPrime[j] = i;
                    }
                }
            }
        }
        for (int i = 2; i <= n; ++i) {
            if (minPrime[i] == 0) {
                minPrime[i] = i;
            }
        }
	}
	static long modInverse(long A, long M)
	{
		long x=extendedEuclid(A,M)[0];
		return (x%M+M)%M;    //x may be negative
	}
	static long[] extendedEuclid(long A, long B) {
		if(B == 0) {
			long d = A;
			long x = 1;
			long y = 0;
			return new long[]{x,y,d};
		}
		else {
			long arr[]=extendedEuclid(B, A%B);
			long temp = arr[0];
			arr[0] = arr[1];
			arr[1] = temp - (A/B)*arr[1];
			return arr;
		}
	}

	static class InputReader {
        private final InputStream stream;
        private final byte[] buf = new byte[8192];
        private int curChar, numChars;
        private SpaceCharFilter filter;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars == -1) {
                throw new InputMismatchException();
            }
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (numChars <= 0) {
                    return -1;
                }
            }
            return buf[curChar++];
        }

        public String nextLine() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            StringBuilder res = new StringBuilder();
            do {
                res.appendCodePoint(c);
                c = read();
            } while (!isEndOfLine(c));
            return res.toString();
        }

        public String readString() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            StringBuilder res = new StringBuilder();
            do {
                res.appendCodePoint(c);
                c = read();
            } while (!isSpaceChar(c));
            return res.toString();
        }

        public long nextLong() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            long res = 0;
            do {
                if (c < '0' || c > '9') {
                    throw new InputMismatchException();
                }
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public int nextInt() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9') {
                    throw new InputMismatchException();
                }
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public int[] nextIntArray(int n) {
            int[] arr = new int[n];
            for (int i = 0; i < n; i++) {
                arr[i] = nextInt();
            }
            return arr;
        }

        public long[] nextLongArray(int n) {
            long[] arr = new long[n];
            for (int i = 0; i < n; i++) {
                arr[i] = nextLong();
            }
            return arr;
        }

        public boolean isSpaceChar(int c) {
            if (filter != null)
                return filter.isSpaceChar(c);
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        private boolean isEndOfLine(int c) {
            return c == '\n' || c == '\r' || c == -1;
        }
        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);
        }
	}
}

/*
 * DA-IICT
 * Author: Jugal Kalal
 */
import java.util.*;
import java.io.*;
import java.math.*;
import java.text.DecimalFormat;
public class Hackerrank{
	static long mod=(long)Math.pow(10,9)+7;
	public static void main(String args[]) {
        new Thread(null, new Runnable() {
            public void run() {
                try{
                    solve();
                    w.close();
                }
                catch(Exception e){
                    e.printStackTrace();
                }
            }
        }, "1", 1 << 26).start();
	}
	static InputReader in;
    static PrintWriter w;
    static void solve(){
        in = new InputReader(System.in);
        w = new PrintWriter(System.out);
        int n=in.nextInt();
        long m=in.nextLong();
        long arr[]=in.nextLongArray(n);
        long ans[]=new long[n+1];
        long max=0;
        for(int i=1;i<=n;i++) {
        		long temp=0;
        		for(int j=0;j<i-1;j++) {
        			if((arr[i-1]+ans[j])%m>temp) {
        				temp=(arr[i-1]+ans[j])%m;
        			}
        		}
        		ans[i]=temp;
        		max=Math.max(max,ans[i]);
        }
        w.println(max);
    }
    static boolean check(int k,String str,char c) {
    		int count=0;
    		for(int i=0;i<k;i++) {
    			if(str.charAt(i)==c) {
    				count++;
    			}
    		}
    		if(count==0) {
    			return false;
    		}
    		for(int i=k;i<str.length();i++) {
    			if(str.charAt(i-k)==c) {
    				count--;
    			}
    			if(str.charAt(i)==c) {
    				count++;
    			}
    			if(count==0) {
    				return false;
    			}
    		}
    		return true;
    }
	static class Pair{
			int parent;
			int type;
			public Pair(int parent,int type) {
				this.parent=parent;
				this.type=type;
			}
	}
	static class Triple{
			int f;
			int s;
			int t;
			public Triple(int f,int s,int t) {
				this.f=f;
				this.s=s;
				this.t=t;
			}
	}
    static int parent[];
    static TreeMap<Integer,ArrayList<Integer>> levels=new TreeMap<>(Collections.reverseOrder());
    static void bfs(int s,int n) {
    		boolean vis[]=new boolean[n];
    		Queue<Integer> queue=new LinkedList<>();
    		Queue<Integer> lev=new LinkedList<>();
    		queue.add(s);
    		vis[s]=true;
    		lev.add(0);
    		parent[0]=-1;
    		while(!queue.isEmpty()) {
    			int top=queue.poll();
    			int l=lev.poll();
    			ArrayList<Integer> temp;
    			if(levels.containsKey(l)) {
    				temp=levels.get(l);
    			}else {
    				temp=new ArrayList<>();
    			}
    			temp.add(top);
    			levels.put(l,temp);
    			for(int v:adj[top]) {
    				if(!vis[v]) {
    					vis[v]=true;
    					lev.add(l+1);
    					queue.add(v);
    				}
    			}
    		}
    }
    static ArrayList<Integer> adj[]; //Adjacency Lists
    static int V;   // No. of vertices
    // Constructor
    static void Graph(int v){
        V = v;
        adj = new ArrayList[v];
        for (int i=0; i<v; ++i){
        		adj[i] = new ArrayList();
        }
    }

    // Function to add an edge into the graph
    static void addEdge(int u,int v){
		adj[u].add(v);
		adj[v].add(u);
    }
//    static long[] isHamiltonian_path(int n){
//    	boolean dp[][]=new boolean[n][1<<n];
//    	long ans[]=new long[n];
//    	long sum[]=new long[n];
//    	for(int i=0;i<n;i++){
//    		dp[i][1<<i]=true;
//    		ans[i]=0;
//    		sum[i]=i+1;
//    	}
//    	for(int mask=0;mask<(1<<n);mask++){
//    		int s=0;
//    		int count=0,temp=mask;
//    		while(temp>0){
//    			s+=1+Math.log(temp&(-temp))/Math.log(2);
//    			temp=temp&(temp-1);
//    			count++;
//    		}
//    		for(int j=0;j<n;j++){
//    			if((mask&(1<<j))>0){
//    				for(int k=0;k<n;k++){
//    					if(j!=k&&(mask&(1<<k))>0&&adj[j][k]&&dp[k][mask^(1<<j)]){
//    						dp[j][mask]=true;
//    						ans[j]=Math.max(ans[j],count-1);
//    						if(ans[j]==count-1){
//    							sum[j]=Math.max(sum[j], s);
//    						}
//    					}
//    				}
//    			}
//    		}
//    	}
//    	return sum;
//    }
//    static void bfs(int s,int n){
//    	boolean visited[]=new boolean[n];
//    	LinkedList<Integer> queue=new LinkedList<Integer>();
//    	queue.add(s);
//    	visited[s]=true;
//    	while(!queue.isEmpty()){
//    		int num=queue.pop();
////    		System.out.println(ans.toString());
//    		for(int i=0;i<adj[num].size();i++){
//    			if(!visited[adj[num].get(i)]){
//    				visited[adj[num].get(i)]=true;
//    				queue.add(adj[num].get(i));
//    			}
//    		}
//    	}
//    }
    static long gcd(long a,long b){
		if(a==0){
			return b;
		}
		return gcd(b%a,a);
	}
    static long power(long base, long exponent, long modulus){
	    long result = 1L;
	    while (exponent > 0) {
	        if (exponent % 2L == 1L)
	            result = (result * base) % modulus;
	        exponent = exponent >> 1;
	        base = (base * base) % modulus;
	    }
	    return result;
	}
    static HashMap<Long,Long> primeFactors(long n){
        HashMap<Long,Long> ans=new HashMap<Long,Long>();
    	// Print the number of 2s that divide n
        while (n%2L==0L)
        {
            if(ans.containsKey(2L)){
            	ans.put(2L,ans.get(2L)+1L);
            }else{
            	ans.put(2L,1L);
            }
            n /= 2L;
        }

        // n must be odd at this point.  So we can
        // skip one element (Note i = i +2)
        for (long i = 3; i <= Math.sqrt(n); i+= 2L)
        {
            // While i divides n, print i and divide n
            while (n%i == 0)
            {
            	if(ans.containsKey(i)){
                	ans.put(i,ans.get(i)+1L);
                }else{
                	ans.put(i,1L);
                }
                n /= i;
            }
        }

        // This condition is to handle the case whien
        // n is a prime number greater than 2
        if (n > 2)
            ans.put(n,1L);
        return ans;
    }
////for marking all prime numbers greater than 1 and less than equal to N
	static boolean[] sieve(int N) {
		 boolean isPrime[]=new boolean[N+1];
		 isPrime[0] = true;
		 isPrime[1] = true;
		 for(int i = 2; i * i <= N; ++i) {
		      if(isPrime[i] == false) {//Mark all the multiples of i as composite numbers
		          for(int j = i * i; j <= N ;j += i)
		              isPrime[j] = true;
		     }
		 }
		 return isPrime;
	}
//  //if  str2 (pattern) is subsequence of str1 (Text) or not
//	static boolean function(String str1,String str2){
//	     str2 = str2.replace("", ".*");  //returns .*a.*n.*n.*a.
//	     return (str1.matches(str2));  // returns true
//	}
    static int Arr[];
    static long size[];
  //modified initialize function:
    static void initialize(int N){
    	Arr=new int[N];
    	size=new long[N];
        for(int i = 0;i<N;i++){
        	Arr[ i ] = i ;
        	size[ i ] = 1;
        }
    }
    static boolean find(int A,int B){
        if( root(A)==root(B) )       //if A and B have same root,means they are connected.
        return true;
        else
        return false;
    }
 // modified root function.
    static void weighted_union(int A,int B,int n){
        int root_A = root(A);
        int root_B = root(B);
        if(size[root_A] < size[root_B ]){
        	Arr[ root_A ] = Arr[root_B];
        	size[root_B] += size[root_A];
        }
        else{
        	Arr[ root_B ] = Arr[root_A];
        	size[root_A] += size[root_B];
        }
    }
    static int root (int i){
        while(Arr[ i ] != i){
            Arr[ i ] = Arr[ Arr[ i ] ] ;
            i = Arr[ i ];
        }
        return i;
    }

	static boolean isPrime(long n) {
		if(n < 2L) return false;
		if(n == 2L || n == 3L) return true;
		if(n%2L == 0 || n%3L == 0) return false;
		long sqrtN = (long)Math.sqrt(n)+1L;
		for(long i = 6L; i <= sqrtN; i += 6L) {
			if(n%(i-1) == 0 || n%(i+1) == 0) return false;
		}
		return true;
	}
//	static HashMap<Integer,Integer> level;;
//	static HashMap<Integer,Integer> parent;
	static int maxlevel=0;

//	static boolean T[][][];
//	static void subsetSum(int input[], int total, int count) {
//        T = new boolean[input.length + 1][total + 1][count+1];
//        for (int i = 0; i <= input.length; i++) {
//        	T[i][0][0] = true;
//        	for(int j = 1; j<=count; j++){
//        		T[i][0][j] = false;
//        	}
//        }
//        int sum[]=new int[input.length+1];
//        for(int i=1;i<=input.length;i++){
//            sum[i]=sum[i-1]+input[i-1];
//        }
//        for (int i = 1; i <= input.length; i++) {
//            for (int j = 1; j <= (int)Math.min(total,sum[i]); j++) {
//            	for (int k = 1; k <= (int)Math.min(i,count); k++){
//            		 if (j >= input[i - 1]) {//Exclude and Include
//                         T[i][j][k] = T[i - 1][j][k] || T[i - 1][j - input[i - 1]][k-1];
//                     } else {
//                         T[i][j][k] = T[i-1][j][k];
//                     }
//            	}
//            }
//        }
//    }
//	static <K,V extends Comparable<? super V>>
//	SortedSet<Map.Entry<K,V>> entriesSortedByValues(Map<K,V> map) {
//	    SortedSet<Map.Entry<K,V>> sortedEntries = new TreeSet<Map.Entry<K,V>>(
//	        new Comparator<Map.Entry<K,V>>() {
//	            @Override public int compare(Map.Entry<K,V> e1, Map.Entry<K,V> e2) {
//	                int res = e2.getValue().compareTo(e1.getValue());
//	                return res != 0 ? res : 1;
//	            }
//	        }
//	    );
//	    sortedEntries.addAll(map.entrySet());
//	    return sortedEntries;
//	}

	//minimum prime factor of all the numbers less than n
    static int minPrime[];
	static void minimumPrime(int n){
		minPrime=new int[n+1];
		minPrime[1]=1;
        for (int i = 2; i * i <= n; ++i) {
            if (minPrime[i] == 0) {         //If i is prime
                for (int j = i * i; j <= n; j += i) {
                    if (minPrime[j] == 0) {
                        minPrime[j] = i;
                    }
                }
            }
        }
        for (int i = 2; i <= n; ++i) {
            if (minPrime[i] == 0) {
                minPrime[i] = i;
            }
        }
	}
	static long modInverse(long A, long M)
	{
		long x=extendedEuclid(A,M)[0];
		return (x%M+M)%M;    //x may be negative
	}
	static long[] extendedEuclid(long A, long B) {
		if(B == 0) {
			long d = A;
			long x = 1;
			long y = 0;
			return new long[]{x,y,d};
		}
		else {
			long arr[]=extendedEuclid(B, A%B);
			long temp = arr[0];
			arr[0] = arr[1];
			arr[1] = temp - (A/B)*arr[1];
			return arr;
		}
	}

	static class InputReader {
        private final InputStream stream;
        private final byte[] buf = new byte[8192];
        private int curChar, numChars;
        private SpaceCharFilter filter;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars == -1) {
                throw new InputMismatchException();
            }
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (numChars <= 0) {
                    return -1;
                }
            }
            return buf[curChar++];
        }

        public String nextLine() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            StringBuilder res = new StringBuilder();
            do {
                res.appendCodePoint(c);
                c = read();
            } while (!isEndOfLine(c));
            return res.toString();
        }

        public String readString() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            StringBuilder res = new StringBuilder();
            do {
                res.appendCodePoint(c);
                c = read();
            } while (!isSpaceChar(c));
            return res.toString();
        }

        public long nextLong() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            long res = 0;
            do {
                if (c < '0' || c > '9') {
                    throw new InputMismatchException();
                }
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public int nextInt() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9') {
                    throw new InputMismatchException();
                }
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public int[] nextIntArray(int n) {
            int[] arr = new int[n];
            for (int i = 0; i < n; i++) {
                arr[i] = nextInt();
            }
            return arr;
        }

        public long[] nextLongArray(int n) {
            long[] arr = new long[n];
            for (int i = 0; i < n; i++) {
                arr[i] = nextLong();
            }
            return arr;
        }

        public boolean isSpaceChar(int c) {
            if (filter != null)
                return filter.isSpaceChar(c);
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        private boolean isEndOfLine(int c) {
            return c == '\n' || c == '\r' || c == -1;
        }
        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);
        }
	}
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.stream.Stream;

public class TestClass implements Runnable {

	static final double time = 1e9;
	static final int MOD = (int) 1e9 + 7;
	static final long mh = Long.MAX_VALUE;
	static final Reader in = new Reader();
	static final PrintWriter out = new PrintWriter(System.out);
	StringBuilder answer = new StringBuilder();

	public static void main(String[] args) {
		new Thread(null, new TestClass(), "persefone", 1 << 28).start();
	}

	@Override
	public void run() {
//		long start = System.nanoTime();
		solve();
		printf();
//		long elapsed = System.nanoTime() - start;
//		out.println("stamp : " + elapsed / time);
//		out.println("stamp : " + TimeUnit.SECONDS.convert(elapsed, TimeUnit.NANOSECONDS));
		close();
	}

	void solve() {
		int n = in.nextInt(), m = in.nextInt();
		long[] a = new long[n];
		for (int i = 0; i < n; i++) a[i] = in.nextInt() % m;

		int l = 1 << (n >> 1), r = 1 << n - (n >> 1);

		long[] b = new long[l];
		create(b, a, n, l);
		Arrays.sort(b);
		long[] c = new long[r];
		create(c, a, n, r);

		long max = 0;
		for (int i = 0; i < c.length; i++) {
			int k = up(b, 0, b.length, m - 1 - c[i]);
			if (k > 0)
				max = Math.max(max, c[i] + b[k - 1]);
		}

		printf(max);
	}

	void create(long[] f, long[] a, int n, int k) {
		for (int i = 1; i < k; i++) {
			long sum = 0;
			for (int j = 0; j < n; j++) {
				int r = i & (1 << j);
				if (r > 0) f[i] += a[j];
			}
		}
	}

	public interface Hash {
		public void computeHashArray();
		public void computeModArray();

	}

	class StringHash implements Hash {
		// length of string s
		private final long MH = Long.MAX_VALUE;
		private int n;
		private char[] ch;
		private long[] hash, mod;
		StringHash(char[] ch) {
			this.ch = ch;
			n = ch.length;
			hash = new long[n + 1];
			mod = new long[n + 1];
			computeHashArray();
			computeModArray();
		}

		StringHash(String s) {
			this(s.toCharArray());
		}

		StringHash(CharSequence s) {
			this(s.toString());
		}

		@Override
		public void computeModArray() {
			mod[0] = 1;
			for (int i = 1; i <= n; i++) mod[i] = (mod[i - 1] * 53) % MH;
		}

		@Override
		public void computeHashArray() {
			for (int i = 0; i < n; i++) hash[i + 1] = (hash[i] * 53 + ch[i] - 'a') % MH;
		}

		public long getHash(int i, int j) {
			return (hash[j] - hash[i] * mod[j - i] + MH * MH) % MH;
		}

		public long getHash(String s) {
			long h = 0;
			for (int i = 0; i < s.length(); i++) h = (h * 53 + s.charAt(i) - 'a') % MH;
			return h;
		}

		public long[] getHashArray() { return hash; }
		public long[] getModArray() { return mod; }
	}

	public interface Manacher {
		public void oddPalindrome();
		public void evenPalindrome();
	}

	class Palindrome implements Manacher {
		private int n;
		private char[] ch;
		private int[] oddPal, evenPal;
		public Palindrome() {}
		public Palindrome(String s) {
			this(s.toCharArray());
		}
		public Palindrome(char[] ch) {
			this.ch = ch;
			n = ch.length;
			oddPal = new int[ch.length];
			evenPal = new int[ch.length];
			oddPalindrome();
			evenPalindrome();
		}

		@Override
		public void oddPalindrome() {
			for (int i = 0, l = 0, r = -1; i < n; i++) {
				int k = i > r ? 1 : Math.min(oddPal[r + l - i], r - i);
				while (0 <= i - k && i + k < n && ch[i - k] == ch[i + k]) k++;
				oddPal[i] = k--;
				if (i + k > r) {
					l = i - k;
					r = i + k;
				}
			}
		}
		@Override
		public void evenPalindrome() {
			for (int i = 0, l = 0, r = -1; i < n; i++) {
				int k = i > r ? 0 : Math.min(evenPal[r + l - i + 1], r - i + 1);
				while (0 <= i - k - 1 && i + k < n && ch[i - k - 1] == ch[i + k]) k++;
				evenPal[i] = k--;
				if (i + k > r) {
					l = i - k - 1;
					r = i + k;
				}
			}
		}
	}

	void printf() {
		out.print(answer);
	}

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

	void printf(Stream<?> str) {
		str.forEach(o -> add(o, " "));
		add("\n");
	}

	void printf(Object... obj) {
		printf(false, obj);
	}

	void printfWithDescription(Object... obj) {
		printf(true, obj);
	}

	private void printf(boolean b, Object... obj) {

		if (obj.length > 1) {
			for (int i = 0; i < obj.length; i++) {
				if (b) add(obj[i].getClass().getSimpleName(), " - ");
				if (obj[i] instanceof Collection<?>) {
					printf((Collection<?>) obj[i]);
				} else if (obj[i] instanceof int[][]) {
					printf((int[][])obj[i]);
				} else if (obj[i] instanceof long[][]) {
					printf((long[][])obj[i]);
				} else if (obj[i] instanceof double[][]) {
					printf((double[][])obj[i]);
				} else printf(obj[i]);
			}
			return;
		}

		if (b) add(obj[0].getClass().getSimpleName(), " - ");
		printf(obj[0]);
	}

	void printf(Object o) {
		if (o instanceof int[])
			printf(Arrays.stream((int[]) o).boxed());
		else if (o instanceof char[])
			printf(new String((char[]) o));
		else if (o instanceof long[])
			printf(Arrays.stream((long[]) o).boxed());
		else if (o instanceof double[])
			printf(Arrays.stream((double[]) o).boxed());
		else if (o instanceof boolean[]) {
			for (boolean b : (boolean[]) o) add(b, " ");
			add("\n");
		}
		else
			add(o, "\n");
	}

	void printf(int[]... obj) {
		for (int i = 0; i < obj.length; i++) printf(obj[i]);
	}

	void printf(long[]... obj) {
		for (int i = 0; i < obj.length; i++) printf(obj[i]);
	}

	void printf(double[]... obj) {
		for (int i = 0; i < obj.length; i++) printf(obj[i]);
	}

	void printf(boolean[]... obj) {
		for (int i = 0; i < obj.length; i++) printf(obj[i]);
	}

	void printf(Collection<?> col) {
		printf(col.stream());
	}

	<T, K> void add(T t, K k) {
		if (t instanceof Collection<?>) {
			((Collection<?>) t).forEach(i -> add(i, " "));
		} else if (t instanceof Object[]) {
			Arrays.stream((Object[]) t).forEach(i -> add(i, " "));
		} else
			add(t);
		add(k);
	}

	<T> void add(T t) {
		answer.append(t);
	}

	@SuppressWarnings("unchecked")
	<T extends Comparable<? super T>> T min(T... t) {
		if (t.length == 0)
			return null;
		T m = t[0];
		for (int i = 1; i < t.length; i++)
			if (t[i].compareTo(m) < 0)
				m = t[i];
		return m;
	}

	@SuppressWarnings("unchecked")
	<T extends Comparable<? super T>> T max(T... t) {
		if (t.length == 0)
			return null;
		T m = t[0];
		for (int i = 1; i < t.length; i++)
			if (t[i].compareTo(m) > 0)
				m = t[i];
		return m;
	}

	int gcd(int a, int b) {
		return (b == 0) ? a : gcd(b, a % b);
	}

	long gcd(long a, long b) {
		return (b == 0) ? a : gcd(b, a % b);
	}

	// c = gcd(a, b) -> extends gcd method: ax + by = c <----> (b % a)p + q = c;
	int[] ext_gcd(int a, int b) {
		if (b == 0) return new int[] {a, 1, 0 };
		int[] vals = ext_gcd(b, a % b);
		int d = vals[0]; // gcd
	    int p = vals[2]; //
		int q = vals[1] - (a / b) * vals[2];
		return new int[] { d, p, q };
	}

	// find any solution of the equation: ax + by = c using extends gcd
	boolean find_any_solution(int a, int b, int c, int[] root) {
		int[] vals = ext_gcd(Math.abs(a), Math.abs(b));
		if (c % vals[0] != 0) return false;
		printf(vals);
		root[0] = c * vals[1] / vals[0];
		root[1] = c * vals[2] / vals[0];
		if (a < 0) root[0] *= -1;
		if (b < 0) root[1] *= -1;
		return true;
	}

	int mod(int x) { return x % MOD; }

	int mod(int x, int y) { return mod(mod(x) + mod(y)); }

	long mod(long x) { return x % MOD; }

	long mod (long x, long y) { return mod(mod(x) + mod(y)); }

	int lw(long[] f, int l, int r, long k) {
		int R = r, m = 0;
		while (l <= r) {
			m = l + r >> 1;
		    if (m == R) return m;
		    if (f[m] >= k) r = m - 1; else l = m + 1;
		}
		return l;
	}

	int up(long[] f, int l, int r, long k) {
		int R = r, m = 0;
		while (l <= r) {
			m = l + r >> 1;
		    if (m == R) return m;
		    if (f[m] > k) r = m - 1; else l = m + 1;
		}
		return l;
	}

	int lw(int[] f, int l, int r, int k) {
		int R = r, m = 0;
		while (l <= r) {
			m = l + r >> 1;
		    if (m == R) return m;
		    if (f[m] >= k) r = m - 1; else l = m + 1;
		}
		return l;
	}

	int up(int[] f, int l, int r, int k) {
		int R = r, m = 0;
		while (l <= r) {
			m = l + r >> 1;
		    if (m == R) return m;
		    if (f[m] > k) r = m - 1; else l = m + 1;
		}
		return l;
	}

	long calc(int base, int exponent) {
		if (exponent == 0) return 1;
		long m = calc(base, exponent >> 1);
		if (exponent % 2 == 0) return m * m % MOD;
		return base * m * m % MOD;
	}

	long power(int base, int exponent) {
		if (exponent == 0) return 1;
		long m = power(base, exponent >> 1);
		if (exponent % 2 == 0) return m * m;
		return base * m * m;
	}

	void swap(int[] a, int i, int j) {
		a[i] ^= a[j];
		a[j] ^= a[i];
		a[i] ^= a[j];
	}

	void swap(long[] a, int i, int j) {
		long tmp = a[i];
		a[i] = a[j];
		a[j] = tmp;
	}

	static class Pair<K extends Comparable<? super K>, V extends Comparable<? super V>>
			implements Comparable<Pair<K, V>> {
		private K k;
		private V v;

		Pair() {}

		Pair(K k, V v) {
			this.k = k;
			this.v = v;
		}

		K getK() { return k; }

		V getV() { return v; }

		void setK(K k) { this.k = k; }

		void setV(V v) { this.v = v; }

		void setKV(K k, V v) {
			this.k = k;
			this.v = v;
		}

		@SuppressWarnings("unchecked")
		@Override
		public boolean equals(Object o) {
			if (this == o) return true;
			if (o == null || !(o instanceof Pair)) return false;
			Pair<K, V> p = (Pair<K, V>) o;
			return k.compareTo(p.k) == 0 && v.compareTo(p.v) == 0;
		}

		@Override
		public int hashCode() {
			int hash = 31;
			hash = hash * 89 + k.hashCode();
			hash = hash * 89 + v.hashCode();
			return hash;
		}

		@Override
		public int compareTo(Pair<K, V> pair) {
			return k.compareTo(pair.k) == 0 ? v.compareTo(pair.v) : k.compareTo(pair.k);
		}

		@Override
		public Pair<K, V> clone() {
			return new Pair<K, V>(this.k, this.v);
		}

		@Override
		public String toString() {
			return String.valueOf(k).concat(" ").concat(String.valueOf(v)).concat("\n");
		}
	}

	static class Reader {
		private BufferedReader br;
		private StringTokenizer st;

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

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

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

		int[] nextIntArray(int n) {
			int[] arr = new int[n];
			for (int i = 0; i < n; i++)
				arr[i] = nextInt();
			return arr;
		}

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

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

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.Collections;
import java.io.InputStream;
import java.util.ArrayList;

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

    static class TaskE {
        public void solve(int testNumber, InputReader in, PrintWriter out) {
            Thread t = new Thread(null, new TaskEThread(in, out), "1", 1 << 23);
            t.start();
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

    static class TaskEThread implements Runnable {
        InputReader in;
        PrintWriter out;

        TaskEThread(InputReader in, PrintWriter out) {
            this.in = in;
            this.out = out;
        }

        public void run() {
            int n = in.nextInt(), m = in.nextInt();
            long a[] = new long[n];
            for (int i = 0; i < n; i++) {
                a[i] = in.nextInt();
            }
            if (n == 1) {
                out.println(a[0] % m);
                return;
            }
            int c = n / 2;
            long a1[] = new long[n - n / 2];
            for (int i = 0; i + c < n; i++) {
                a1[i] = a[i + c];
            }
            int cr = n - n / 2;
            ArrayList<Long> al = new ArrayList<>();
            long fans = 0;
            for (int i = 1; i < (1 << cr); i++) {
                long ans = 0;
                for (int j = 0; j < cr; j++) {
                    if (((1 << j) & i) > 0) {
                        ans = (ans + a1[j]) % m;
                    }
                }
                fans = Math.max(fans, ans);
                al.add(ans);
            }
            Collections.sort(al);
            for (int i = 1; i < (1 << c); i++) {
                long ans = 0;
                for (int j = 0; j < c; j++) {
                    if (((1 << j) & i) > 0) {
                        ans = (ans + a[j]) % m;
                    }
                }
                int id = Collections.binarySearch(al, m - ans - 1);
                if (id < 0) {
                    id = -id - 2;
                }
                if (id > 0) {
                    ans = ans + al.get(id);
                }
                fans = Math.max(fans, ans);
            }
            out.println(fans);
        }

    }

    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private InputReader.SpaceCharFilter filter;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars == -1)
                throw new InputMismatchException();

            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }

                if (numChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }

        public int nextInt() {
            int c = read();

            while (isSpaceChar(c))
                c = read();

            int sgn = 1;

            if (c == '-') {
                sgn = -1;
                c = read();
            }

            int res = 0;
            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            }
            while (!isSpaceChar(c));

            return res * sgn;
        }

        public boolean isSpaceChar(int c) {
            if (filter != null)
                return filter.isSpaceChar(c);
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);

        }

    }
}

import java.awt.List;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.function.BinaryOperator;

public class WCS {

	public static TreeSet <Integer> firstK;
	public static int ans;

	public static int calc(int[] a, long bitmask, int m) {
		int val = 0;
		int p = 0;
		while(bitmask > 0) {
			if(bitmask % 2 == 1)
				val = (val + a[p]) % m;
			p ++;
			bitmask >>= 1;
		}
		return val;
	}

	public static void compute(int[] a, int current, long bitmask, int m) {
		int val = calc(a, bitmask, m);
		if(current == a.length / 2)
			firstK.add(val);
		else if(current == a.length - 1)
			ans = Math.max(ans, val + firstK.lower(m - val));
		else {
			compute(a, current + 1, bitmask, m);
			compute(a, current + 1, bitmask | (1L << current), m);
		}
	}

	public static void main(String[] args) {
		int n = in.nextInt();
		int m = in.nextInt();
		int[] a = new int[n];
		for(int i = 0; i < n; i ++)
			a[i] = in.nextInt();
		firstK = new TreeSet <Integer> ();
		ans = 0;
		compute(a, 0, 0L, m);
		compute(a, a.length / 2 + 1, 0L, m);
		System.out.println(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();
}

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);
                  if(u>=0 && u<al2.size())
                  t=Math.max(t,(al1.get(i)+al2.get(u))%m);
            }

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

            System.out.println(t);
      }
}

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>();
            for(int i=0;i<=l1;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<=l2;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-1l-al1.get(i);
                  long y=2*m-1l-al1.get(i);
                  int u=Collections.binarySearch(al2,x);
                  int v=Collections.binarySearch(al2,y);
                  if(u>=0 || v>=0)
                  { t=m-1; break; }

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

            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);
            TreeSet<Integer> hs = new TreeSet<>();
            TreeSet<Integer> hs1 = new TreeSet<>();
            hs.add(0);
            for (int i = 0; i < n / 2; i++) {
                ArrayList<Integer> aa = new ArrayList<>();
                for (int j : hs) {
                    aa.add((j + a[i]) % m);
                }
                hs.addAll(aa);
            }
            hs1.add(0);
            for (int i = n / 2; i < n; i++) {
                ArrayList<Integer> aa = new ArrayList<>();
                for (int j : hs1) {
                    aa.add((j + a[i]) % m);
                }
                hs1.addAll(aa);
            }

            Iterator<Integer> h11 = hs.iterator();
            Iterator<Integer> h22 = hs1.iterator();
            int res = 0;

            int[] h1 = new int[hs.size()], h2 = new int[hs1.size()];
            {
                int i = 0;
                while (h11.hasNext()) h1[i++] = h11.next();
            }
            {
                int i = 0;
                while (h22.hasNext()) h2[i++] = h22.next();
            }
            {
                int j = h2.length - 1;
                for (int i = 0; i < h1.length; i++) {
                    while (j >= 0 && h1[i] + h2[j] > m) {
                        j--;
                    }
                    if (j < 0) break;
                    res = Math.max(res, h1[i] + h2[j]);
                }
            }
            for (int j : hs) {
                res = Math.max(res, j);
            }
            for (int j : hs1) {
                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 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);
            TreeSet<Integer> hs = new TreeSet<>();
            TreeSet<Integer> hs1 = new TreeSet<>();
            hs.add(0);
            for (int i = 0; i < n / 2; i++) {
                ArrayList<Integer> aa = new ArrayList<>();
                for (int j : hs) {
                    aa.add((j + a[i]) % m);
                }
                hs.addAll(aa);
            }
            hs1.add(0);
            for (int i = n / 2; i < n; i++) {
                ArrayList<Integer> aa = new ArrayList<>();
                for (int j : hs1) {
                    aa.add((j + a[i]) % m);
                }
                hs1.addAll(aa);
            }

            Iterator<Integer> h11 = hs.iterator();
            Iterator<Integer> h22 = hs1.descendingIterator();
            int res = 0;

            int[] h1 = new int[hs.size()], h2 = new int[hs1.size()];
            {
                int i = 0;
                while (h11.hasNext()) h1[i++] = h11.next();
            }
            {
                int i = 0;
                while (h22.hasNext()) h2[i++] = h22.next();
            }
            {
                int j = h2.length - 1;
                for (int i = 0; i < h1.length; i++) {
                    while (j >= 0 && h1[i] + h2[j] > m) {
                        j--;
                    }
                    if (j < 0) break;
                    res = Math.max(res, h1[i] + h2[j]);
                }
            }
            for (int j : hs) {
                res = Math.max(res, j);
            }
            for (int j : hs1) {
                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, 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.util.*;
import java.io.*;

public class MaximumSubsequence {
    public static void main(String[] args) {
        FastScanner scanner = new FastScanner();
        PrintWriter out = new PrintWriter(System.out, false);
        //Meet in the middle practice
        int n = scanner.nextInt();
        long m = scanner.nextInt();
        int szl = n/2;
        int szr = n-n/2;
        long[] left = new long[szl];
        long[] right = new long[szr];
        for(int i = 0; i < n; i++) {
            if (i < szl) {
                left[i] = scanner.nextInt();
            } else {
                right[i-szl] = scanner.nextInt();
            }
        }
        if (n == 1) {
            out.println(right[0] % m);
            out.flush();
            return;
        }
        long[] lvals = new long[1 << szl];
        long[] rvals = new long[1 << szr];
        //do left half
        int maxMask = 1 << szl;
        for(int mask = 0; mask < maxMask; mask++) {
            long cur = 0;
            for(int i = 0; i < szl; i++) {
                if (((1 << i) & mask) > 0) cur += left[i];
            }
            lvals[mask] = cur % m;
        }
        //do right half
        maxMask = 1 << szr;
        for(int mask = 0; mask < maxMask; mask++) {
            long cur = 0;
            for(int i = 0; i < szr; i++) {
                if (((1 << i) & mask) > 0) cur += right[i];
            }
            rvals[mask] = cur % m;
        }
        //sort the values
        Arrays.sort(rvals);
        Arrays.sort(lvals);
        //traditional two pointers meet in the middle combintion
        int lp = 1;
        int rp = maxMask-1;
        int lmaxMask = 1 << szl;
        long ans = 0;
        while(lp != lmaxMask -1 || rp != 0) {
            long tot = rvals[rp] + lvals[lp];
            if (tot >= m) {
                ans = Math.max(ans, tot - m);
                if (rp != 0) rp--;
                else lp++;
            } else {
                ans = Math.max(ans, tot);
                if (lp != lmaxMask-1) lp++;
                else rp--;
            }
        }
        ans = Math.max(ans, lvals[lmaxMask-1]);
        out.println(ans);
        out.flush();
    }

    public static class FastScanner {
        BufferedReader br;
        StringTokenizer st;

        public FastScanner(Reader in) {
            br = new BufferedReader(in);
        }

        public FastScanner() {
            this(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 readNextLine() {
            String str = "";
            try {
                str = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }
    }
}

//package info.stochastic;//package info.stochastic;

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

public class E {

    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskE solver = new TaskE();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskE {
        Set<Integer> calcSets(int[] a, int m) {
            Set<Integer> ans = new HashSet<>();
            for (int i = 0; i < (1 << a.length); i++) {
                int set = 0;
                int index = 1;
                for (int j = 0; j < a.length; j++) {
                    if ((i & (index << j)) > 0) {
                        set += a[j];
                    }
                }
                ans.add(set % m);
            }
            return ans;
        }

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

            int leftSize = n / 2;
            int rightSize = n / 2 + n % 2;

            int[] al = new int[leftSize];
            int[] ar = new int[rightSize];

            for (int i = 0; i < leftSize; i++) {
                al[i] = in.nextInt();
            }

            for (int i = 0; i < rightSize; i++) {
                ar[i] = in.nextInt();
            }

            Set<Integer> leftSet = calcSets(al, m);
            Set<Integer> rightSet = calcSets(ar, m);
            Integer[] right = new Integer[rightSet.size()];
            rightSet.toArray(right);
            Arrays.sort(right);

            int ans = 0;
            for (int fromLeft: leftSet) {
                int l = 0;
                int r = right.length - 1;
                int max = 0;
                while (l <= r) {
                    int mid = (l + r) >> 1;
                    if ((fromLeft + right[mid]) < m) {
                        max = fromLeft + right[mid];
                        l = mid + 1;
                    } else {
                        r = mid - 1;
                    }
                }
                ans = Math.max(ans, max);
            }

            out.print(ans);
        }

    }

    static class InputReader {
        public BufferedReader reader;
        public StringTokenizer tokenizer;

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

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

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

import java.io.*;
import java.util.StringTokenizer;
import java.util.TreeSet;

public class Main {
    public static void main(String[] args) throws IOException {
        Scanner sc = new Scanner(System.in);
        PrintWriter out = new PrintWriter(System.out);
        int n = sc.nextInt();
        int m = sc.nextInt();
        int k = n / 2;
        int l = n - k;
        int[] a1 = new int[k];
        int[] a2 = new int[l];
        for (int i = 0; i < k; i++)
            a1[i] = sc.nextInt();
        for (int i = 0; i < k; i++)
            a2[i] = sc.nextInt();
        TreeSet<Integer> one = getAns(a1, k, m);
        TreeSet<Integer> two = getAns(a2, l, m);
        int max = 0;
        for (int num : one) {
            int allowed = m-num;
            Integer found = two.lower(allowed);
            if (found!=null) max = Math.max(max,found+num);
        }
        out.println(max);
        out.flush();
        out.close();
    }

    static TreeSet<Integer> getAns(int[] a, int n, int m) {
        TreeSet<Integer> ans = new TreeSet<>();
        for (int mask = 0; mask < (1 << n); mask++) {
            int sum = 0;
            for (int i = 0; i < n; i++) {
                if ((mask & (1 << i)) != 0) sum = (sum + a[i]) % m;
            }
            ans.add(sum);
        }
        return ans;
    }

    static class Scanner {
        StringTokenizer st;
        BufferedReader br;

        public Scanner(InputStream system) {
            br = new BufferedReader(new InputStreamReader(system));
        }

        public Scanner(String file) throws Exception {
            br = new BufferedReader(new FileReader(file));
        }

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

        public String nextLine() throws IOException {
            return br.readLine();
        }

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

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

        public char nextChar() throws IOException {
            return next().charAt(0);
        }

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

        public boolean ready() throws IOException {
            return br.ready();
        }

        public void waitForInput() throws InterruptedException {
            Thread.sleep(3000);
        }
    }
}

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.TreeSet;

public class MaximumSubsequence {
	public static void main(String[] args) {
		InputReader r = new InputReader(System.in);
		int n = r.nextInt();
		int m = r.nextInt();
		int[] arr = new int[n];
		for (int i = 0; i < arr.length; i++) {
			arr[i] = r.nextInt() % m;
		}
		int half = n / 2;
		int other = n - half;
		TreeSet<Integer> set = new TreeSet<Integer>();
		int res = 0;
		for (int i = 0; i < (1 << other); i++) {
			int sum = 0;
			for (int j = 0; j < other; j++) {
				if ((i & (1 << j)) > 0) {
					sum += arr[half + j];
					sum %= m;
				}
			}
			res = Math.max(res, sum);
			set.add(sum);
		}
		for (int i = 0; i < (1 << half); i++) {
			int sum = 0;
			for (int j = 0; j < half; j++) {
				if ((i & (1 << j)) > 0) {
					sum += arr[j];
					sum %= m;
				}
			}
			res = Math.max(res, sum);
			int need = m - sum;
			Integer get = set.lower(need);
			if (get != null) {
				res = Math.max(res, (need + sum) % m);
			}
		}
		System.out.println(res);
	}

	static class InputReader {
		private BufferedReader reader;
		private StringTokenizer tokenizer;

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

		public InputReader(FileReader stream) {
			reader = new BufferedReader(stream);
			tokenizer = null;
		}

		public String nextLine() {
			try {
				return reader.readLine();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return null;
			}
		}

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

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

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

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

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.TreeSet;
import java.util.ArrayList;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author Sanket Makani
 */
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);
        TaskE solver = new TaskE();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskE {
        public void solve(int testNumber, InputReader sc, PrintWriter w) {

            int n = sc.nextInt();
            long m = sc.nextLong();

            TreeSet<Long> set1 = new TreeSet<>();
            TreeSet<Long> set2 = new TreeSet<>();

            ArrayList<Integer> list = new ArrayList<>();

            int arr[] = new int[n];

            for (int i = 0; i < n; i++)
                arr[i] = sc.nextInt();

            for (int i = 0; i < n / 2; i++)
                list.add(arr[i]);

            getPermutation(list, set1, m);

            list.clear();

            for (int i = n / 2; i < n; i++)
                list.add(arr[i]);

            getPermutation(list, set2, m);

            long max = -1;

            max = Math.max(set1.last(), set2.last());

            for (long in : set1) {
                max = Math.max(max, in);
                long searchFor = m - in - 1;
                Long key = set2.floor(searchFor);
                if (key != null)
                    max = Math.max((in + key) % m, max);
            }

            w.println(max);
        }

        private void getPermutation(ArrayList<Integer> list, TreeSet<Long> set, long mod) {
            int total = list.size();

            int pow = (int) Math.pow(2, total);

            for (int i = 1; i < pow; i++) {
                long curr = 1;

                for (int j = 0; j < total; j++) {
                    if ((i & (1 << j)) != 0) {
                        curr *= list.get(j);
                        curr %= mod;
                    }
                }

                set.add(curr);
            }

        }

    }

    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private InputReader.SpaceCharFilter filter;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars == -1)
                throw new InputMismatchException();

            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }

                if (numChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }

        public int nextInt() {
            int c = read();

            while (isSpaceChar(c))
                c = read();

            int sgn = 1;

            if (c == '-') {
                sgn = -1;
                c = read();
            }

            int res = 0;
            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            }
            while (!isSpaceChar(c));

            return res * sgn;
        }

        public long nextLong() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            long res = 0;

            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            }
            while (!isSpaceChar(c));
            return res * sgn;
        }

        public boolean isSpaceChar(int c) {
            if (filter != null)
                return filter.isSpaceChar(c);
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);

        }

    }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.TreeSet;
import java.util.ArrayList;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author Sanket Makani
 */
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);
        TaskE solver = new TaskE();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskE {
        public void solve(int testNumber, InputReader sc, PrintWriter w) {

            int n = sc.nextInt();
            long m = sc.nextLong();

            TreeSet<Long> set1 = new TreeSet<>();
            TreeSet<Long> set2 = new TreeSet<>();

            ArrayList<Long> list = new ArrayList<>();

            long arr[] = new long[n];

            for (int i = 0; i < n; i++)
                arr[i] = sc.nextInt();

            for (int i = 0; i < n / 2; i++)
                list.add(arr[i]);

            getPermutation(list, set1, m);

            list.clear();

            for (int i = n / 2; i < n; i++)
                list.add(arr[i]);

            getPermutation(list, set2, m);

            long max = -1;

            max = Math.max(set1.last(), set2.last());

            for (long in : set1) {
                max = Math.max(max, in);
                long searchFor = m - in - 1;
                Long key = set2.floor(searchFor);
                if (key != null)
                    max = Math.max((in + key) % m, max);
            }

            w.println(max);
        }

        private void getPermutation(ArrayList<Long> list, TreeSet<Long> set, long mod) {
            int total = list.size();

            int pow = (int) Math.pow(2, total);
            set.add(0L);
            for (int i = 1; i < pow; i++) {
                long curr = 1;

                for (int j = 0; j < total; j++) {
                    if ((i & (1 << j)) != 0) {
                        curr *= list.get(j);
                        curr %= mod;
                    }
                }

                set.add(curr);
            }

        }

    }

    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private InputReader.SpaceCharFilter filter;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars == -1)
                throw new InputMismatchException();

            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }

                if (numChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }

        public int nextInt() {
            int c = read();

            while (isSpaceChar(c))
                c = read();

            int sgn = 1;

            if (c == '-') {
                sgn = -1;
                c = read();
            }

            int res = 0;
            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            }
            while (!isSpaceChar(c));

            return res * sgn;
        }

        public long nextLong() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            long res = 0;

            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            }
            while (!isSpaceChar(c));
            return res * sgn;
        }

        public boolean isSpaceChar(int c) {
            if (filter != null)
                return filter.isSpaceChar(c);
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);

        }

    }
}

import java.io.*;
import java.util.*;
import java.util.function.Consumer;

public class Solution {

    static MyScanner sc;
    private static PrintWriter out;
    static long M2 = 1_000_000_000L + 7;

    public static void main(String[] s) throws Exception {
        StringBuilder stringBuilder = new StringBuilder();

        if (stringBuilder.length() == 0) {
            sc = new MyScanner(System.in);
        } else {
            sc = new MyScanner(new BufferedReader(new StringReader(stringBuilder.toString())));
        }

        out = new PrintWriter(new OutputStreamWriter(System.out));

        initData();
        solve();
        out.flush();
    }

    private static void initData() {

    }

    private static void solve() throws IOException {
        int n = sc.nextInt();
        int m = sc.nextInt();
        int[] r12 = sc.na(n);

        out.println(solve2(r12, 0, n, m));
    }

    private static long solve2(int[] r12, int i, int n, int m) {
        if (i == n) return 0;
        if (i + 1 == n) return r12[i] %  m;
        int x1 = 0;
        int mid = (i + n) / 2;

        TreeSet<Integer> tx1 = rd(r12, mid, n, m);
        TreeSet<Integer> tx2 = rd(r12, i, mid, m);

        int m1 = tx2.last();
        int m2 = tx2.first();
        for (int k : tx1) {
            Integer x2 = tx2.lower(k);
            x1 = Math.max(x1, (m1 + k) % m);
            x1 = Math.max(x1, (m2 + k) % m);
            if (x2 != null)
                x1 = Math.max(x1, (x2 + k) % m);
        }

        return Math.max(x1, Math.max(solve2(r12, mid, n, m), solve2(r12, i, mid, m)));
    }

    private static TreeSet<Integer> rd(int[] r12, int i, int mid, int m) {
        TreeSet<Integer> kk = new TreeSet<>();
        for (int t = i; t < mid; t++) {
            TreeSet<Integer> next = new TreeSet<>(kk);
            for (int l : kk) {
                next.add((l + r12[t]) % m);
            }
            next.add(r12[t] % m);
            kk = next;
        }
        return kk;
    }

    private static final class LogTreePar {

        private final int[] levels;
        private final int[][] parents;

        public LogTreePar(int n) {
            levels = new int[n];
            parents = new int[n][19];
            Arrays.fill(levels, -1);
            for (int[] x : parents) {
                Arrays.fill(x, -1);
            }
        }

        public boolean ispar(int f, int l) {
            if (levels[f] >= levels[l]) return false;
            int diff = levels[l] - levels[f];
            return up(l, diff) == f;
        }

        private int up(int item, int diff) {
            int r = 0;
            while (diff > 0 && item >= 0) {
                if (isset(diff, r)) {
                    diff ^= 1 << r;
                    item = parents[item][r];
                }
                r++;
            }
            return item;
        }

        public void add(int item, int parent) {
            parents[item][0] = parent;
            clt(item);
        }

        protected void clt(int item) {
            levels[item] = levels[parents[item][0]] + 1;
            for (int l = 1; l < 19; l++) {
                if (parents[item][l - 1] == -1) break;
                parents[item][l] = parents[parents[item][l - 1]][l - 1];
            }
        }

        public int lca(int f, int l) {
            if (levels[f] > levels[l]) {
                return lca(l, f);
            }
            return lca1(f, up(l, levels[l] - levels[f]));
        }

        private int lca1(int f1, int f2) {
            for (int r = 18; r >= 0 && f1 != f2; r--) {
                if (parents[f1][r] != parents[f2][r]) {
                    f1 = parents[f1][r];
                    f2 = parents[f2][r];
                }
            }
            return f1 == f2 ? f1 : parents[f1][0];
        }
    }

    private static class P {
        private boolean b;
        private final int ind;
        private final int parent;

        public P(int i, boolean b, int par) {
            this.ind = i;
            this.b = b;
            this.parent = par;

        }
    }

    private static void dfs(int start, int[][] neig, Consumer<int[]> onAdd, Consumer<int[]> onRemove) {
        ArrayList<P> toVisit = new ArrayList<P>(3000);
        toVisit.add(new P(start, true, -1));
        boolean[] vis = new boolean[neig.length];
        vis[start] = true;
        int[] level = new int[neig.length];
        while (toVisit.size() > 0) {
            P ppr = toVisit.remove(toVisit.size() - 1);
            if (!ppr.b) {
                onRemove.accept(new int[]{ppr.ind, level[ppr.ind], ppr.parent});
                continue;
            }
            ppr.b = false;
            int i = ppr.ind;
            toVisit.add(ppr);
            onAdd.accept(new int[]{ppr.ind, level[ppr.ind], ppr.parent});
            for (int kk : neig[i]) {
                if (!vis[kk]) {
                    vis[kk] = true;
                    level[kk] = level[i] + 1;
                    toVisit.add(new P(kk, true, i));
                }
            }
        }

    }

    private static int[][] tr(int n) {
        int[][] x = new int[2][n - 1];
        for (int i = 0; i < n - 1; i++) {
            x[0][i] = sc.nextInt() - 1;
            x[1][i] = sc.nextInt() - 1;
        }
        return pn(x, n);
    }

    private static int[][] pn(int[][] x, int n) {
        int[] ct = new int[n];
        int[][] res = new int[n][];
        for (int v : x[0]) {
            ct[v]++;
        }
        for (int v : x[1]) {
            ct[v]++;
        }
        for (int l = 0; l < n; l++) {
            res[l] = new int[ct[l]];
        }
        for (int i = 0; i < x[0].length; i++) {
            res[x[0][i]][--ct[x[0][i]]] = x[1][i];
            res[x[1][i]][--ct[x[1][i]]] = x[0][i];
        }
        return res;
    }

    private static boolean isset(long i, int k) {
        return (i & (1 << k)) > 0;
    }

    private static void solveT() throws IOException {
        int t = sc.nextInt();
        while (t-- > 0) {
            solve();
        }
    }

    private static long gcd(long l, long l1) {
        if (l > l1) return gcd(l1, l);
        if (l == 0) return l1;
        return gcd(l1 % l, l);
    }

    private static long pow(long a, long b, long m) {
        if (b == 0) return 1;
        if (b == 1) return a;
        long pp = pow(a, b / 2, m);
        pp *= pp;
        pp %= m;
        return (pp * (b % 2 == 0 ? 1 : a)) % m;
    }

    static class MyScanner {
        BufferedReader br;
        StringTokenizer st;

        MyScanner(BufferedReader br) {
            this.br = br;
        }

        public MyScanner(InputStream in) {
            this(new BufferedReader(new InputStreamReader(in)));
        }

        void findToken() {
            while (st == null || !st.hasMoreTokens()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }

        String next() {
            findToken();
            return st.nextToken();
        }

        Integer[] nab(int n) {
            Integer[] k = new Integer[n];
            for (int i = 0; i < n; i++) {
                k[i] = sc.fi();
            }
            return k;
        }

        int[] na(int n) {
            int[] k = new int[n];
            for (int i = 0; i < n; i++) {
                k[i] = sc.fi();
            }
            return k;
        }

        long[] nl(int n) {
            long[] k = new long[n];
            for (int i = 0; i < n; i++) {
                k[i] = sc.nextLong();
            }
            return k;
        }

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

        int fi() {
            String t = next();
            int cur = 0;
            boolean n = t.charAt(0) == '-';
            for (int a = n ? 1 : 0; a < t.length(); a++) {
                cur = cur * 10 + t.charAt(a) - '0';
            }
            return n ? -cur : cur;
        }

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

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

}

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

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

    static class E {
        private long[] getSums(int[] a, int from, int to, long mod) {
            int n = to - from;
            long[] res = new long[1 << n];
            for (int mask = 0; mask < 1 << n; mask++) {
                long sum = 0;
                for (int i = 0; i < n; i++) {
                    if ((mask & (1 << i)) > 0) {
                        sum += a[i];
                    }
                }
                res[mask] = sum % mod;
            }
            return res;
        }

        public void solve(int testNumber, FastScanner in, PrintWriter out) {
            int n = in.ni(), m = in.ni();
            long mod = m;
            int[] a = in.na(n);
            for (int i = 0; i < n; i++) {
                a[i] %= m;
            }
            long[] p1 = getSums(a, 0, n / 2, mod);
            long[] p2 = getSums(a, n / 2, n, mod);
            Arrays.sort(p1);
            Arrays.sort(p2);
            long ans = 0;
            int right = p2.length - 1;
            for (int i = 0; i < n / 2; i++) {
                while (right >= 0 && p1[i] + p2[right] >= mod) {
                    right--;
                }
                ans = Math.max(ans, p1[i] + p2[right]);
            }
            out.println(ans);

        }

    }

    static class FastScanner {
        private BufferedReader in;
        private StringTokenizer st;

        public FastScanner(InputStream stream) {
            in = new BufferedReader(new InputStreamReader(stream));
        }

        public String ns() {
            while (st == null || !st.hasMoreTokens()) {
                try {
                    String rl = in.readLine();
                    if (rl == null) {
                        return null;
                    }
                    st = new StringTokenizer(rl);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return st.nextToken();
        }

        public int ni() {
            return Integer.parseInt(ns());
        }

        public int[] na(int n) {
            int[] a = new int[n];
            for (int i = 0; i < n; i++) a[i] = ni();
            return a;
        }

    }
}

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

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

    static class E {
        private long[] getSums(int[] a, int from, int to, long mod) {
            int n = to - from;
            long[] res = new long[1 << n];
            for (int mask = 0; mask < 1 << n; mask++) {
                long sum = 0;
                for (int i = 0; i < n; i++) {
                    if ((mask & (1 << i)) > 0) {
                        sum += a[i];
                    }
                }
                res[mask] = sum % mod;
            }
            return res;
        }

        public void solve(int testNumber, FastScanner in, PrintWriter out) {
            int n = in.ni(), m = in.ni();
            long mod = m;
            int[] a = in.na(n);
            for (int i = 0; i < n; i++) {
                a[i] %= m;
            }
            if (n == 1) {
                out.println(a[0]);
                return;
            }
            long[] p1 = getSums(a, 0, n / 2, mod);
            long[] p2 = getSums(a, n / 2, n, mod);
            Arrays.sort(p1);
            Arrays.sort(p2);
//        System.out.println("Arrays.toString(p1) = " + Arrays.toString(p1));
//        System.out.println("Arrays.toString(p2) = " + Arrays.toString(p2));
            long ans = 0;
            int right = p2.length - 1;
            for (int i = 0; i < p1.length; i++) {
                while (right >= 0 && p1[i] + p2[right] >= mod) {
                    right--;
                }
                ans = Math.max(ans, p1[i] + p2[right]);
            }
            out.println(ans);

        }

    }

    static class FastScanner {
        private BufferedReader in;
        private StringTokenizer st;

        public FastScanner(InputStream stream) {
            in = new BufferedReader(new InputStreamReader(stream));
        }

        public String ns() {
            while (st == null || !st.hasMoreTokens()) {
                try {
                    String rl = in.readLine();
                    if (rl == null) {
                        return null;
                    }
                    st = new StringTokenizer(rl);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return st.nextToken();
        }

        public int ni() {
            return Integer.parseInt(ns());
        }

        public int[] na(int n) {
            int[] a = new int[n];
            for (int i = 0; i < n; i++) a[i] = ni();
            return a;
        }

    }
}

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.TreeSet;

public class E888 {

	TreeSet<Integer> go(int[] a, int mod) {
		int n = a.length;
		TreeSet<Integer> set = new TreeSet<>();
		for(int mask = 0; mask < 1 << n; ++mask) {
			int sum = 0;
			for(int i = 0; i < n; ++i) {
				if((mask & (1 << i)) == 0) continue;
				sum += a[i];
				sum %= mod;
			}
			set.add(sum);
		}
		return set;
	}

	public void solve(JoltyScanner in, PrintWriter out) {
		int n = in.nextInt();
		int mod = in.nextInt();
		int[] a = new int[n];
		for(int i = 0; i < n; ++i) a[i] = in.nextInt();
		int[] left = new int[n / 2];
		int[] right = new int[n - n / 2];
		for(int i = 0; i < n; ++i) {
			if(i < left.length) left[i] = a[i];
			else right[i - left.length] = a[i];
		}
		TreeSet<Integer> asums = go(left, mod);
		TreeSet<Integer> bsums = go(right, mod);
		int ans = 0;
		for(int x : asums) {
			int need = mod - x; //adding this will give 0
			Integer best = bsums.lower(need);
			if(best == null) best = bsums.last();
			int sum = need + best;
			sum %= mod;
			ans = Math.max(ans, sum);
		}
		out.println(ans);
	}

	public static void main(String[] args) {
		JoltyScanner in = new JoltyScanner();
		PrintWriter out = new PrintWriter(System.out);
		new E888().solve(in, out);
		out.close();
	}

	static class JoltyScanner {
		public int BS = 1<<16;
		public char NC = (char)0;
		byte[] buf = new byte[BS];
		int bId = 0, size = 0;
		char c = NC;
		double num = 1;
		BufferedInputStream in;

		public JoltyScanner() {
			in = new BufferedInputStream(System.in, BS);
		}

		public JoltyScanner(String s) throws FileNotFoundException {
			in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
		}

		public char nextChar(){
			while(bId==size) {
				try {
					size = in.read(buf);
				}catch(Exception e) {
					return NC;
				}
				if(size==-1)return NC;
				bId=0;
			}
			return (char)buf[bId++];
		}

		public int nextInt() {
			return (int)nextLong();
		}

		public long nextLong() {
			num=1;
			boolean neg = false;
			if(c==NC)c=nextChar();
			for(;(c<'0' || c>'9'); c = nextChar()) {
				if(c=='-')neg=true;
			}
			long res = 0;
			for(; c>='0' && c <='9'; c=nextChar()) {
				res = (res<<3)+(res<<1)+c-'0';
				num*=10;
			}
			return neg?-res:res;
		}

		public double nextDouble() {
	        while(c!='.'&&c!='-'&&(c <'0' || c>'9')) c = nextChar();
	        boolean neg = c=='-';
	        if(neg)c=nextChar();
	        boolean fl = c=='.';
	        double cur = nextLong();
	        if(fl) return neg ? -cur/num : cur/num;
	        if(c == '.') {
	            double next = nextLong();
	            return neg ? -cur-next/num : cur+next/num;
	        }
	        else return neg ? -cur : cur;
	    }

		public String next() {
			StringBuilder res = new StringBuilder();
			while(c<=32)c=nextChar();
			while(c>32) {
				res.append(c);
				c=nextChar();
			}
			return res.toString();
		}

		public String nextLine() {
			StringBuilder res = new StringBuilder();
			while(c<=32)c=nextChar();
			while(c!='\n') {
				res.append(c);
				c=nextChar();
			}
			return res.toString();
		}

		public boolean hasNext() {
			if(c>32)return true;
			while(true) {
				c=nextChar();
				if(c==NC)return false;
				else if(c>32)return true;
			}
		}
	}

}

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 long modifiedBinarySearch(Long[] A,long k)
	{

		int from = 0, to = A.length-1,ans=-1 ;
		while(from<=to )
		{
			int m = (from+to)/2 ;
			// System.out.println("from: "+from+" to :"+to+"m :"+m) ;
			if(A[m]==k)
				return A[m] ;
			if(A[m]<k)
			{
				from = m+1 ;
				ans=m;
			}
			else
			{
				to = m-1 ;
			}
		}
		// return A[from] ;
		if(ans==-1)
			return 0;
		else
			return A[ans];

	}
	static HashSet<Long> setChecker(long[] A,long m)
	{
		// boolean[] M = new boolean[m] ;
		HashSet<Long> H = new HashSet<Long>() ;
		int set_size = A.length ;
		long power_set_size = pow(2,set_size) ;
		for(int i=0;i<power_set_size;i++)
		{
			long 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(Long[] A)
	{
		for(int i=0;i<A.length;i++)
		{
			System.out.print(A[i]+" ") ;
		}
		System.out.println() ;
	}
	static void arrayPrinter(long[] A)
	{
		for(int i=0;i<A.length;i++)
		{
			System.out.print(A[i]+" ") ;
		}
		System.out.println() ;
	}
	static long maxPossibleValue(long[] A,long m)
	{
		if(m==1)
			return 0 ;
		int half_length = A.length/2 ;
		long[] first_half = new long[half_length] ;
		long[] second_half  = new long[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<Long> H1 = setChecker(first_half,m) ;
		HashSet<Long> H2  = setChecker(second_half,m) ;
		Long[] A1 = H1.toArray(new Long[H1.size()]) ;
		Long[] A2 = H2.toArray(new Long[H2.size()]) ;
		System.out.println("Before sorting:") ;

		arrayPrinter(A1) ;
		arrayPrinter(A2) ;
		Arrays.sort(A1) ;
		Arrays.sort(A2) ;
		System.out.println("After sorting:") ;
		arrayPrinter(A1) ;
		arrayPrinter(A2) ;
		long maxPV = 0 ;
		for(int i=0;i<A1.length;i++)
		{
			long ans = modifiedBinarySearch(A2,m-A1[i]-1) ;
			// System.out.println("Searched for :"+(m-A1[i]-1)+" and mBS returned ans :"+ans) ;
			if(maxPV<(A1[i]+ans)%m)
			{
				maxPV = (A1[i]+ans)%m ;
				System.out.println("maxPV is :"+maxPV) ;
			}
		}
		// 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() ;

		return maxPV ;
	}
	public static void main(String args[]) throws Exception
	{

		Scanner in = new Scanner(System.in) ;
		int size = in.nextInt() ;

		long m = in.nextLong() ;
		long[] A = new long[size] ;
		long maxPV = 0 ;
		for(int i=0;i<size;i++)
		{
			A[i] = in.nextLong() ;
			// if(maxPV<A[i]%m)
				// maxPV = A[i]%m ;
		}
		long ans1 = maxPossibleValue(A,m) ;
		long ans = ans1>maxPV?ans1:maxPV ;
		System.out.println(ans) ;

		// int k = in.nextInt() ;
		// System.out.println(modifiedBinarySearch(A,k)) ;

	}
}

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 int modifiedBinarySearch(Integer[] A,int k)
	{

		int from = 0, to = A.length-1,ans=-1 ;
		while(from<=to )
		{
			int m = (from+to)/2 ;
			// System.out.println("from: "+from+" to :"+to+"m :"+m) ;
			if(A[m]==k)
				return A[m] ;
			if(A[m]<k)
			{
				from = m+1 ;
				ans=m;
			}
			else
			{
				to = m-1 ;
			}
		}
		// return A[from] ;
		if(ans==-1)
			return 0;
		else
			return A[ans];

	}
	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(Integer[] A)
	{
		for(int i=0;i<A.length;i++)
		{
			System.out.print(A[i]+" ") ;
		}
		System.out.println() ;
	}
	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()]) ;
		// System.out.println("Before sorting:") ;

		// arrayPrinter(A1) ;
		// arrayPrinter(A2) ;
		Arrays.sort(A1) ;
		Arrays.sort(A2) ;
		// System.out.println("After sorting:") ;
		// arrayPrinter(A1) ;
		// arrayPrinter(A2) ;
		int maxPV = 0 ;
		for(int i=0;i<A1.length;i++)
		{
			int ans = modifiedBinarySearch(A2,m-A1[i]-1) ;
			// System.out.println("Searched for :"+(m-A1[i]-1)+" and mBS returned ans :"+ans) ;
			if(maxPV<(A1[i]+ans)%m)
			{
				maxPV = (A1[i]+ans)%m ;
				// System.out.println("maxPV is :"+maxPV) ;
			}
		}
		// 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() ;

		return maxPV ;
	}
	public static void main(String args[]) throws Exception
	{

		Scanner in = new Scanner(System.in) ;
		int size = in.nextInt() ;

		int m = in.nextInt() ;
		int[] A = new int[size] ;
		int maxPV = 0 ;
		for(int i=0;i<size;i++)
		{
			A[i] = in.nextInt() ;
			// if(maxPV<A[i]%m)
				// maxPV = A[i]%m ;
		}
		int ans1 = maxPossibleValue(A,m) ;
		int ans = ans1>maxPV?ans1:maxPV ;
		System.out.println(ans) ;

		// int k = in.nextInt() ;
		// System.out.println(modifiedBinarySearch(A,k)) ;

	}
}

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 boolean[] setChecker(int[] A,int m)
	{
		boolean[] M = new boolean[m] ;
		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] ;
			}
			M[(sum%m)] = true ;
		}
		return M ;
	}
	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;i++)
		{
			second_half[i-half_length] = A[i] ;
		}
		boolean[] M1 = setChecker(first_half,m) ;
		boolean[] M2 = setChecker(second_half,m) ;
		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 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 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;i++)
		{
			second_half[i-half_length] = A[i] ;
		}
		boolean[] M1 = setChecker(first_half,m) ;
		boolean[] M2 = setChecker(second_half,m) ;
		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 int modifiedBinarySearch(Integer[] A,int k)
	{

		int from = 0, to = A.length-1,ans=-1 ;
		while(from<=to )
		{
			int m = (from+to)/2 ;
			// System.out.println("from: "+from+" to :"+to+"m :"+m) ;
			if(A[m]==k)
				return A[m] ;
			if(A[m]<k)
			{
				from = m+1 ;
				ans=m;
			}
			else
			{
				to = m-1 ;
			}
		}
		// return A[from] ;
		if(ans==-1)
			return 0;
		else
			return A[ans];

	}
	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()]) ;
		Arrays.sort(A1) ;
		Arrays.sort(A2) ;

		int maxPV = 0 ;
		for(int i=0;i<A1.length;i++)
		{
			int ans = modifiedBinarySearch(A2,m-A1[i]-1) ;
			if(maxPV<(A[i]+ans)%m)
				maxPV = (A[i]+ans)%m ;
		}
		// 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() ;

		return maxPV ;
	}
	public static void main(String args[]) throws Exception
	{

		Scanner in = new Scanner(System.in) ;
		int size = in.nextInt() ;

		int m = in.nextInt() ;
		int[] A = new int[size] ;
		int maxPV = 0 ;
		for(int i=0;i<size;i++)
		{
			A[i] = in.nextInt() ;
			if(maxPV<A[i]%m)
				maxPV = A[i]%m ;
		}
		int ans1 = maxPossibleValue(A,m) ;
		int ans = ans1>maxPV?ans1:maxPV ;
		System.out.println(ans) ;

		// int k = in.nextInt() ;
		// System.out.println(modifiedBinarySearch(A,k)) ;

	}
}

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

public class Main implements Runnable {
    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private SpaceCharFilter filter;
        private BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars==-1)
                throw new InputMismatchException();

            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                }
                catch (IOException e) {
                    throw new InputMismatchException();
                }

                if(numChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }

        public String nextLine() {
            String str = "";
            try {
                str = br.readLine();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }
        public int nextInt() {
            int c = read();

            while(isSpaceChar(c))
                c = read();

            int sgn = 1;

            if (c == '-') {
                sgn = -1;
                c = read();
            }

            int res = 0;
            do {
                if(c<'0'||c>'9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            }
            while (!isSpaceChar(c));

            return res * sgn;
        }

        public long nextLong() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            long res = 0;

            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            }
            while (!isSpaceChar(c));
            return res * sgn;
        }

        public double nextDouble() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            double res = 0;
            while (!isSpaceChar(c) && c != '.') {
                if (c == 'e' || c == 'E')
                    return res * Math.pow(10, nextInt());
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            }
            if (c == '.') {
                c = read();
                double m = 1;
                while (!isSpaceChar(c)) {
                    if (c == 'e' || c == 'E')
                        return res * Math.pow(10, nextInt());
                    if (c < '0' || c > '9')
                        throw new InputMismatchException();
                    m /= 10;
                    res += (c - '0') * m;
                    c = read();
                }
            }
            return res * sgn;
        }

        public String readString() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            StringBuilder res = new StringBuilder();
            do {
                res.appendCodePoint(c);
                c = read();
            }
            while (!isSpaceChar(c));

            return res.toString();
        }

        public boolean isSpaceChar(int c) {
            if (filter != null)
                return filter.isSpaceChar(c);
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public String next() {
            return readString();
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);
        }
    }
    public static void main(String args[]) throws Exception {
        new Thread(null, new Main(),"Main",1<<26).start();
    }

    static long gcd(long a,long b){ if(b==0)return a;return gcd(b,a%b); }
    static long modPow(long a,long p,long m){ if(a==1)return 1;long ans=1;while (p>0){ if(p%2==1)ans=(ans*a)%m;a=(a*a)%m;p>>=1; }return ans; }
    static long modInv(long a,long m){return modPow(a,m-2,m);}

    public void run() {
        InputReader sc = new InputReader(System.in);
        PrintWriter out = new PrintWriter(System.out);

        int n=sc.nextInt();
        int k=sc.nextInt();
        int a[]=new int[n];
        for (int i = 0; i <n ; i++) {
            a[i]=sc.nextInt();
        }
        int N_Half=n/2;
        int firsthalf[]=new int[1<<N_Half];
        for (int i = 0; i <(1<<N_Half) ; i++) {
            for (int j = 0; j <N_Half ; j++) {
                if((i&(1<<j))!=0){
                    firsthalf[i]+=a[j];
                }
            }
            firsthalf[i]%=k;
        }
        Arrays.sort(firsthalf);

        int maainans=Integer.MIN_VALUE;
        for (int i = 0; i <1<<(n-N_Half) ; i++) {
            int temp=0;
            for (int j = 0; j <(n-N_Half) ; j++) {
                if((i&(1<<j))!=0){
                    temp+=a[j+N_Half];
                }
            }
            temp%=k;
            int l=0,r=(1<<N_Half)-1,want=k-temp-1,ans=0;
            while (l<=r){
                int mid=(l+r)>>1;
                if(firsthalf[mid]<=want){
                    ans=firsthalf[l];
                    l=mid+1;
                }
                else{
                    r=mid-1;
                }
            }
            maainans=Math.max(maainans,(ans+temp)%k);
        }

        out.println(maainans);

        out.close();
    }

}

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

public class Main implements Runnable {
    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private SpaceCharFilter filter;
        private BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars==-1)
                throw new InputMismatchException();

            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                }
                catch (IOException e) {
                    throw new InputMismatchException();
                }

                if(numChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }

        public String nextLine() {
            String str = "";
            try {
                str = br.readLine();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }
        public int nextInt() {
            int c = read();

            while(isSpaceChar(c))
                c = read();

            int sgn = 1;

            if (c == '-') {
                sgn = -1;
                c = read();
            }

            int res = 0;
            do {
                if(c<'0'||c>'9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            }
            while (!isSpaceChar(c));

            return res * sgn;
        }

        public long nextLong() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            long res = 0;

            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            }
            while (!isSpaceChar(c));
            return res * sgn;
        }

        public double nextDouble() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            double res = 0;
            while (!isSpaceChar(c) && c != '.') {
                if (c == 'e' || c == 'E')
                    return res * Math.pow(10, nextInt());
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            }
            if (c == '.') {
                c = read();
                double m = 1;
                while (!isSpaceChar(c)) {
                    if (c == 'e' || c == 'E')
                        return res * Math.pow(10, nextInt());
                    if (c < '0' || c > '9')
                        throw new InputMismatchException();
                    m /= 10;
                    res += (c - '0') * m;
                    c = read();
                }
            }
            return res * sgn;
        }

        public String readString() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            StringBuilder res = new StringBuilder();
            do {
                res.appendCodePoint(c);
                c = read();
            }
            while (!isSpaceChar(c));

            return res.toString();
        }

        public boolean isSpaceChar(int c) {
            if (filter != null)
                return filter.isSpaceChar(c);
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public String next() {
            return readString();
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);
        }
    }
    public static void main(String args[]) throws Exception {
        new Thread(null, new Main(),"Main",1<<26).start();
    }

    static long gcd(long a,long b){ if(b==0)return a;return gcd(b,a%b); }
    static long modPow(long a,long p,long m){ if(a==1)return 1;long ans=1;while (p>0){ if(p%2==1)ans=(ans*a)%m;a=(a*a)%m;p>>=1; }return ans; }
    static long modInv(long a,long m){return modPow(a,m-2,m);}

    public void run() {
        InputReader sc = new InputReader(System.in);
        PrintWriter out = new PrintWriter(System.out);

        int n=sc.nextInt();
        int k=sc.nextInt();
        int a[]=new int[n];
        for (int i = 0; i <n ; i++) {
            a[i]=sc.nextInt();
        }
        int N_Half=n/2;
        int firsthalf[]=new int[1<<N_Half];
        for (int i = 0; i <(1<<N_Half) ; i++) {
            for (int j = 0; j <N_Half ; j++) {
                if((i&(1<<j))!=0){
                    firsthalf[i]+=a[j];
                }
            }
            firsthalf[i]%=k;
        }
        Arrays.sort(firsthalf);

        int maainans=Integer.MIN_VALUE;
        for (int i = 0; i <1<<(n-N_Half) ; i++) {
            int temp=0;
            for (int j = 0; j <(n-N_Half) ; j++) {
                if((i&(1<<j))!=0){
                    temp+=a[j+N_Half];
                }
            }
            temp%=k;
            int l=0,r=(1<<N_Half)-1,want=k-temp-1,ans=0;
            while (l<=r){
                int mid=(l+r)>>1;
                if(firsthalf[mid]<=want){
                    ans=firsthalf[l];
                    l=mid+1;
                }
                else{
                    r=mid-1;
                }
            }
            maainans=Math.max(maainans,ans+temp);
        }

        out.println(maainans);

        out.close();
    }

}

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

public class Main implements Runnable {
    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private SpaceCharFilter filter;
        private BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars==-1)
                throw new InputMismatchException();

            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                }
                catch (IOException e) {
                    throw new InputMismatchException();
                }

                if(numChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }

        public String nextLine() {
            String str = "";
            try {
                str = br.readLine();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }
        public int nextInt() {
            int c = read();

            while(isSpaceChar(c))
                c = read();

            int sgn = 1;

            if (c == '-') {
                sgn = -1;
                c = read();
            }

            int res = 0;
            do {
                if(c<'0'||c>'9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            }
            while (!isSpaceChar(c));

            return res * sgn;
        }

        public long nextLong() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            long res = 0;

            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            }
            while (!isSpaceChar(c));
            return res * sgn;
        }

        public double nextDouble() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            double res = 0;
            while (!isSpaceChar(c) && c != '.') {
                if (c == 'e' || c == 'E')
                    return res * Math.pow(10, nextInt());
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            }
            if (c == '.') {
                c = read();
                double m = 1;
                while (!isSpaceChar(c)) {
                    if (c == 'e' || c == 'E')
                        return res * Math.pow(10, nextInt());
                    if (c < '0' || c > '9')
                        throw new InputMismatchException();
                    m /= 10;
                    res += (c - '0') * m;
                    c = read();
                }
            }
            return res * sgn;
        }

        public String readString() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            StringBuilder res = new StringBuilder();
            do {
                res.appendCodePoint(c);
                c = read();
            }
            while (!isSpaceChar(c));

            return res.toString();
        }

        public boolean isSpaceChar(int c) {
            if (filter != null)
                return filter.isSpaceChar(c);
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public String next() {
            return readString();
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);
        }
    }
    public static void main(String args[]) throws Exception {
        new Thread(null, new Main(),"Main",1<<26).start();
    }

    static long gcd(long a,long b){ if(b==0)return a;return gcd(b,a%b); }
    static long modPow(long a,long p,long m){ if(a==1)return 1;long ans=1;while (p>0){ if(p%2==1)ans=(ans*a)%m;a=(a*a)%m;p>>=1; }return ans; }
    static long modInv(long a,long m){return modPow(a,m-2,m);}

    public void run() {
        InputReader sc = new InputReader(System.in);
        PrintWriter out = new PrintWriter(System.out);

        int n=sc.nextInt();
        int k=sc.nextInt();
        int a[]=new int[n];
        for (int i = 0; i <n ; i++) {
            a[i]=sc.nextInt();
        }
        int N_Half=n/2;
        long firsthalf[]=new long[1<<N_Half];
        for (int i = 0; i <(1<<N_Half) ; i++) {
            for (int j = 0; j <N_Half ; j++) {
                if((i&(1<<j))!=0){
                    firsthalf[i]+=a[j];
                }
            }
            firsthalf[i]%=k;
        }
        Arrays.sort(firsthalf);

        long maainans=Long.MIN_VALUE;
        for (int i = 0; i <1<<(n-N_Half) ; i++) {
            long temp=0;
            for (int j = 0; j <(n-N_Half) ; j++) {
                if((i&(1<<j))!=0){
                    temp+=a[j+N_Half];
                }
            }
            temp%=k;
            int l=0,r=(1<<N_Half)-1;long want=k-temp-1,ans=0;
            while (l<=r){
                int mid=(l+r)>>1;
                if(firsthalf[mid]<=want){
                    ans=firsthalf[l];
                    l=mid+1;
                }
                else{
                    r=mid-1;
                }
            }
            maainans=Math.max(maainans,ans+temp);
        }

        out.println(maainans);

        out.close();
    }

}

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

public class E888 {

	int n;
	long m;
	int l;
	int r;

	private void solve() throws Exception {
		n = nextInt();
		m = nextInt();
		l = n/2;
		r = n-l;
		long[] al = new long[l];
		for(int i = 0; i < l; i++) al[i] = nextLong()%m;
		long[] ar = new long[r];
		for(int i = 0; i < r; i++) ar[i] = nextLong()%m;
		long[] part1 = doit(al);
		long[] part2 = doit(ar);
		long best = 0;
		for(int i = 0; i < part1.length; i++){
			int left = 0;
			int right = r;
			while(left < right-1) {
				int mid = (left+right)/2;
				if(part1[i] + part2[mid] < m) left = mid;
				else right = mid;
			}
			best = Math.max(best, (part1[i]+part2[left])%m);
			left = Math.min(r-1, right+1);
			right = r;
			while(left < right-1) {
				int mid = (left+right)/2;
				if(part1[i] + part2[mid] < 2*m) left = mid;
				else right = mid;
			}
			best = Math.max(best, (part1[i]+part2[left])%m);
		}
		out.println(best);
	}

	long[] doit(long[] a) {
		int n = a.length;
		long[] res = new long[(1<<n)];
		for(int i = 0; i < (1<<n); i++) {
			int ii = i;
			for(int j = 0; j < n; j++, ii >>= 1) if((ii^1) == 1) res[i] = (res[i]+a[j])%m;
		}
		Arrays.sort(res);
		return res;
	}

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

	private BufferedReader in;
	private PrintWriter out;
	private StringTokenizer tokenizer;

	public void run() {
		try {
			in = new BufferedReader(new InputStreamReader(System.in));
			tokenizer = null;
			out = new PrintWriter(System.out);
			solve();
			in.close();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(1);
		}
	}

	private int nextInt() throws IOException {
		return Integer.parseInt(nextToken());
	}

	private long nextLong() throws IOException {
		return Long.parseLong(nextToken());
	}

	private float nextFloat() throws IOException {
		return Float.parseFloat(nextToken());
	}

	private String nextLine() throws IOException {
		return new String(in.readLine());
	}

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

}

import java.io.*;
import java.util.*;
public class Main
{

	private void solve()throws Exception
	{
		int n=nextInt();
		int m=nextInt();
		int a[]=new int[n+1];
		for(int i=1;i<=n;i++)
			a[i]=nextInt();

		int bigmask=(1<<(n/2))-1;
		ArrayList<Integer> list=new ArrayList<>();
		for(int mask=0;mask<=bigmask;mask++)
		{
			int sum=0;
			for(int j=1;j<=n/2;j++)
			{
				if(((mask>>(j-1))&1)==1)
					sum=(sum+a[j])%m;
			}
			list.add(sum);
		}

		Collections.sort(list);
		list=removeDup(list);

		bigmask=(1<<((n+1)/2))-1;
		int ans=0;
		for(int mask=0;mask<=bigmask;mask++)
		{
			int sum=0;
			for(int j=n/2+1;j<=n;j++)
			{
				if(((mask>>(j-n/2-1))&1)==1)
					sum=(sum+a[j])%m;
			}
			ans=Math.max(sum+floor(m-sum-1,list),(sum+list.get(list.size()-1))%m);
		}
		out.println(ans);
	}
	ArrayList<Integer> removeDup(ArrayList<Integer> list)
	{
		int prev=-1;
		ArrayList<Integer> list1=new ArrayList<>();
		for(int i:list)
			if(i!=prev)
			{
				list1.add(i);
				prev=i;
			}
		return list1;
	}
	int floor(int x,ArrayList<Integer> list)
	{
		int low=0,high=list.size()-1,ans=0;
		while(low<=high)
		{
			int mid=(low+high)/2;
			if(list.get(mid)<=x)
			{
				ans=mid;
				low=mid+1;
			}
			else
				high=mid-1;
		}
		return ans;
	}

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

	public void run()throws Exception
	{
		br=new BufferedReader(new InputStreamReader(System.in));
		st=null;
		out=new PrintWriter(System.out);

		solve();

		br.close();
		out.close();
	}
	public static void main(String args[])throws Exception{
		new Main().run();
	}
	BufferedReader br;
	StringTokenizer st;
	PrintWriter out;
	String nextToken()throws Exception{
		while(st==null || !st.hasMoreTokens())
		st=new StringTokenizer(br.readLine());
		return st.nextToken();
	}
	String nextLine()throws Exception{
		return br.readLine();
	}
	int nextInt()throws Exception{
		return Integer.parseInt(nextToken());
	}
	long nextLong()throws Exception{
		return Long.parseLong(nextToken());
	}
	double nextDouble()throws Exception{
		return Double.parseDouble(nextToken());
	}
}

import java.io.*;
import java.util.*;
public class Main
{

	private void solve()throws Exception
	{
		int n=nextInt();
		int m=nextInt();
		int a[]=new int[n+1];
		for(int i=1;i<=n;i++)
			a[i]=nextInt();

		int bigmask=(1<<(n/2))-1;
		ArrayList<Integer> list=new ArrayList<>();
		for(int mask=0;mask<=bigmask;mask++)
		{
			int sum=0;
			for(int j=1;j<=n/2;j++)
			{
				if(((mask>>(j-1))&1)==1)
					sum=(sum+a[j])%m;
			}
			list.add(sum);
		}

		Collections.sort(list);
		list=removeDup(list);

		bigmask=(1<<((n+1)/2))-1;
		int ans=0;
		for(int mask=0;mask<=bigmask;mask++)
		{
			int sum=0;
			for(int j=n/2+1;j<=n;j++)
			{
				if(((mask>>(j-n/2-1))&1)==1)
					sum=(sum+a[j])%m;
			}
			ans=Math.max(sum+floor(m-sum-1,list),(sum+list.get(list.size()-1))%m);
		}
		out.println(ans);
	}
	ArrayList<Integer> removeDup(ArrayList<Integer> list)
	{
		int prev=-1;
		ArrayList<Integer> list1=new ArrayList<>();
		for(int i:list)
			if(i!=prev)
			{
				list1.add(i);
				prev=i;
			}
		return list1;
	}
	int floor(int x,ArrayList<Integer> list)
	{
		int low=0,high=list.size()-1,ans=-1;
		while(low<=high)
		{
			int mid=(low+high)/2;
			if(list.get(mid)<=x)
			{
				ans=mid;
				low=mid+1;
			}
			else
				high=mid-1;
		}
		return ans;
	}

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

	public void run()throws Exception
	{
		br=new BufferedReader(new InputStreamReader(System.in));
		st=null;
		out=new PrintWriter(System.out);

		solve();

		br.close();
		out.close();
	}
	public static void main(String args[])throws Exception{
		new Main().run();
	}
	BufferedReader br;
	StringTokenizer st;
	PrintWriter out;
	String nextToken()throws Exception{
		while(st==null || !st.hasMoreTokens())
		st=new StringTokenizer(br.readLine());
		return st.nextToken();
	}
	String nextLine()throws Exception{
		return br.readLine();
	}
	int nextInt()throws Exception{
		return Integer.parseInt(nextToken());
	}
	long nextLong()throws Exception{
		return Long.parseLong(nextToken());
	}
	double nextDouble()throws Exception{
		return Double.parseDouble(nextToken());
	}
}

/**
 * ******* Created  on 8/4/20 4:52 AM*******
 */

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

public class E888 implements Runnable {

    private static final int MAX = (int) (1E5 + 5);
    private static final int MOD = (int) (1E9 + 7);
    private static final long Inf = (long) (1E14 + 10);
    private static final double eps = (double) (1E-9);

    private void solve() throws IOException {
        int n = reader.nextInt();
        int m = reader.nextInt();
        int st = (n+1)/2;
        long[] a = new long[50];
        for(int i=0;i<n;i++){
            a[i] =reader.nextInt();
        }
        TreeSet<Long> set = new TreeSet<>();
        for(int i=0;i<(1<<st);i++){
            long cur =0;
            for(int j=0;j<n;j++)
                if((i&(1<<j)) !=0)
                    cur = (cur+a[i])%m;
            set.add(cur);
        }

        int st2 = n-st;
        long ans =0;
        for(int i=0;i<(1<<st2);i++){
            long cur =0;
            for(int j=0;j<n;j++)
                if((i&(1<<j))!=0)
                    cur =(cur+ a[j+st] )%m;
            long val = (m-1- cur);
            Long val2 = set.floor(val);
            if(val2 == null)
                val2 = Long.valueOf(0);
            ans = Math.max(ans, val2 + cur );
        }
        writer.println(ans);
    }

    public static void main(String[] args) throws IOException {
        try (Input reader = new StandardInput(); PrintWriter writer = new PrintWriter(System.out)) {
            new E888().run();
        }
    }

    StandardInput reader;
    PrintWriter writer;

    @Override
    public void run() {
        try {
            reader = new StandardInput();
            writer = new PrintWriter(System.out);
            solve();
            reader.close();
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    interface Input extends Closeable {
        String next() throws IOException;

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

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

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

        default int[] readIntArray() throws IOException {
            return readIntArray(nextInt());
        }

        default int[] readIntArray(int size) throws IOException {
            int[] array = new int[size];
            for (int i = 0; i < array.length; i++) {
                array[i] = nextInt();
            }
            return array;
        }

        default long[] readLongArray(int size) throws IOException {
            long[] array = new long[size];
            for (int i = 0; i < array.length; i++) {
                array[i] = nextLong();
            }
            return array;
        }
    }

    private static class StandardInput implements Input {
        private final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        private StringTokenizer stringTokenizer;

        @Override
        public void close() throws IOException {
            reader.close();
        }

        @Override
        public String next() throws IOException {
            if (stringTokenizer == null || !stringTokenizer.hasMoreTokens()) {
                stringTokenizer = new StringTokenizer(reader.readLine());
            }
            return stringTokenizer.nextToken();
        }
    }
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

public class Main {

    public static void main(String[] args) {
        MyScanner in = new MyScanner();
        int n = in.nextInt();
        int m = in.nextInt();
        int divider = 2;
        Set<Integer>[] parts = new HashSet[divider];
        for (int i = 0; i < divider; i++) {
            parts[i] = new HashSet<>();
        }

        int max = 0;
        for (int i = 0; i < n; i++) {
            Set set = parts[i % divider];
            int v = in.nextInt() % m;
            Iterator<Integer> iterator = set.iterator();
            List<Integer> list = new ArrayList<>();
            list.add(v);
            while (iterator.hasNext()) {
                int v2 = (iterator.next() + v) % m;
                if (set.contains(v2)) continue;
                list.add(v2);
            }
            set.addAll(list);
        }

        List<Integer> list1 = new ArrayList<>(parts[0]);
        list1.add(0);
        Collections.sort(list1);

        for (int v : parts[1]) {
            int index = Collections.binarySearch(list1, m - v - 1);

            if(index >= 0){
                max = m - 1;
                break;
            } else {
                max = Math.max(max, list1.get(-index - 2) + v);
            }
        }

        System.out.println(max);
    }

    static class MyScanner {
        BufferedReader br;
        StringTokenizer st;

        public MyScanner() {
            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;
        }
    }
}

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

public class EC32P5
{
    private static long[] arr;

    public static void main(String args[])
    {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        long m = in.nextLong();
        arr = new long[n+1];

        arr[0] = 0;
        for(int i=1; i<n+1; i++){
            arr[i] = in.nextLong();
        }

        //sort arr in terms of size mod m

        for(int i=1; i<arr.length; i++)
        {
            arr[i] = arr[i] % m;

        }

        Arrays.sort(arr);

        //set arr[0] as m-1-arr[n+1]

        arr[0] = m-1;

        //reverse for loop arr[0] isn't smallest, arr[0] -= largest arr[i]<arr[0]

        for(int i=n; i>0; i--)
        {
            if(arr[0] % m >= arr[i])
            {
                arr[0] -= arr[i];
            }
        }
        //output m-1-arr[0]

        System.out.println(m-1-arr[0]);
    }

    //public static long convert(int[] array)
    //{
    //    long counter = 0L;
    //
    //    for(int i=1; i<arr.length; i++)
    //    {
    //        counter += array[i]*arr[i];
    //    }

    //    return counter;
    //}
}

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

public class EC32P5
{
    private static long[] arr;

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

        int n = in.nextInt();
        int m = in.nextInt();

        int[] arr1 = new int[n/2];
        int[] arr2 = new int[n - n/2];

        for(int i=0; i<n/2; i++)
        {
            arr1[i] = in.nextInt();
        }

        for(int i=0; i<n - n/2; i++)
        {
            arr2[i] = in.nextInt();
        }

        int[] sum1 = sums_on_subarray(arr1, n/2, 0, m);
        int[] sum2 = sums_on_subarray(arr2, n- n/2, 0, m);
        Arrays.sort(sum1);

        int counter = 0;;

        for(int i=0; i<sum2.length; i++)
        {
            int sum = 0;
            int key = Arrays.binarySearch(sum1, m-1-sum2[i]);
            int key2 = Arrays.binarySearch(sum1, m-1);

            if(key<0)
            {
                key = -(key+2);
            }

            if(key2<0)
            {
                key2 = -(key2 + 2);
            }

            sum = sum2[i] + sum1[key];
            sum = (sum2[i] + sum1[key2]) % m;

            if(sum > counter)
            {
                counter = sum;
            }

        }

        System.out.println(counter);
    }

    public static int[] sums_on_subarray(int[] a, int size, int from, int m) {
        int[] sums = new int[1 << size];
        for (int i = 0; i < 1 << size; i++) {
            int sum = 0;
            for (int j = 0; j < size; j++) {
                if ((i & 1 << j) > 0) {
                    sum = (sum + a[j + from]) % m;
                }
            }

            sums[i] = sum;
        }

        return sums;
    }

}

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

public class Main {
    static final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
    static final int[][] STEPS = {{1, 2}, {1, -2}, {-1, 2}, {-1, -2}, {2, 1}, {2, -1}, {-2, 1}, {-2, -1}};

    void solve() throws IOException {
        int n = readInt(), m = readInt();
        int[] a = readIntArray(n);
        if (n == 1) {
            out.print(a[0] % m);
            return;
        }
        int n1 = n / 2;
        int n2 = n - n / 2;
        ArrayList<Integer> list1 = new ArrayList<Integer>();
        ArrayList<Integer> list2 = new ArrayList<Integer>();
        ArrayList<Integer> added = new ArrayList<Integer>();
        list1.add(0);
        list1.add(a[0]);
        for (int i = 0; i < n1; i++) {
            for (int j : list1) {
                added.add((j + a[i]) % m);
            }
            for (int j : added) {
                list1.add(j);
            }
        }
        added.clear();
        added.add(0);
        added.add(a[n1]);
        for (int i = n1; i < n; i++) {
            for (int j : list1) {
                added.add((j + a[i]) % m);
            }
            for (int j : added) {
                list2.add(j);
            }
        }
        Collections.sort(list1);
        Collections.sort(list2);
        int flag = list2.size() - 1;
        int answer = 0;
        for (int i : list1) {
            while (i + list2.get(flag) >= m && flag > 0) flag--;
            if (flag < 0) break;
            answer = maxInt(answer, (i + list2.get(flag)) % m);
        }
        out.print(answer);
    }

    void init() throws FileNotFoundException {
        if (ONLINE_JUDGE) {
            in = new BufferedReader(new InputStreamReader(System.in));
            out = new PrintWriter(System.out);
        } else {
            in = new BufferedReader(new FileReader("input.txt"));
            out = new PrintWriter("output.txt");
        }
        tok = new
                StringTokenizer("");
    }

    int minInt(int... values) {
        int min = Integer.MAX_VALUE;
        for (int value : values) {
            min = Math.min(min, value);
        }
        return min;
    }

    int maxInt(int... values) {
        int max = Integer.MIN_VALUE;
        for (int value : values) {
            max = Math.max(max, value);
        }
        return max;
    }

    long minLong(long... values) {
        long min = Long.MAX_VALUE;
        for (long value : values) {
            min = Math.min(min, value);
        }
        return min;
    }

    long maxLong(long... values) {
        long max = Long.MIN_VALUE;
        for (long value : values) {
            max = Math.max(max, value);
        }
        return max;
    }

    boolean checkIndex(int index, int size) {
        return (0 <= index && index < size);
    }

    int abs(int a) {
        return Math.abs(a);
    }

    int gcd(int a, int b) {
        if (a * b == 0) return maxInt(a, b);
        return gcd(minInt(a, b), maxInt(a, b) % minInt(a, b));
    }

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

    BufferedReader in;
    PrintWriter out;
    StringTokenizer tok;

    void run() {
        try {
            long timeStart = System.currentTimeMillis();

            init();
            solve();

            out.close();

            long timeEnd = System.currentTimeMillis();
            System.err.println("time = " + (timeEnd - timeStart) + " compiled");
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(-1);
        }

    }

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

    String delimiter = " ";

    String readString() throws IOException {
        while (!tok.hasMoreTokens()) {
            String nextLine = readLine();
            if (null == nextLine)
                return null;

            tok = new StringTokenizer(nextLine);
        }

        return tok.nextToken(delimiter);
    }

    int[] readIntArray(int b) {
        int a[] = new int[b];
        for (int i = 0; i < b; i++) {
            try {
                a[i] = readInt();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return a;
    }

    long[] readLongArray(int b) {
        long a[] = new long[b];
        for (int i = 0; i < b; i++) {
            try {
                a[i] = readLong();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return a;
    }

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

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

    void sortArrayInt(int[] a) {
        Integer arr[] = new Integer[a.length];
        for (int i = 0; i < a.length; i++) {
            arr[i] = a[i];
        }
        Arrays.sort(arr);
        for (int i = 0; i < a.length; i++) {
            a[i] = arr[i];
        }
    }

    void sortArrayLong(long[] a) {
        Long arr[] = new Long[a.length];
        for (int i = 0; i < a.length; i++) {
            arr[i] = a[i];
        }
        Arrays.sort(arr);
        for (int i = 0; i < a.length; i++) {
            a[i] = arr[i];
        }
    }

}

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

public class Main {
    static final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
    static final int[][] STEPS = {{1, 2}, {1, -2}, {-1, 2}, {-1, -2}, {2, 1}, {2, -1}, {-2, 1}, {-2, -1}};

    void solve() throws IOException {
        int n = readInt(), m = readInt();
        int[] a = new int[n];
        for (int i = 0; i < n; i++) {
            a[i] = readInt() % m;
        }
        if (n == 1) {
            out.print(a[0] % m);
            return;
        }
        int n1 = n / 2;
        int n2 = n - n / 2;
        ArrayList<Integer> list1 = new ArrayList<Integer>();
        ArrayList<Integer> list2 = new ArrayList<Integer>();
        ArrayList<Integer> added = new ArrayList<Integer>();
        list1.add(a[0]);
        for (int i = 0; i <= n1; i++) {
            for (int j : list1) {
                added.add((j + a[i]) % m);
            }
            for (int j : added) {
                list1.add(j);
            }
            list1.add(a[i]);
            added.clear();
        }
        added.clear();
        added.add(a[n1]);
        for (int i = n1 + 1; i < n; i++) {
            for (int j : list2) {
                added.add((j + a[i]) % m);
            }
            for (int j : added) {
                list2.add(j);

            }
            list2.add(a[i]);
            added.clear();
        }
        TreeSet<Integer> set1 = new TreeSet<Integer>();
        TreeSet<Integer> set2 = new TreeSet<Integer>();
        for (int i : list1) {
            set1.add(i);
        }
        for (int j : list2) {
            set2.add(j);
        }
        int last = 0;
        int answer =maxInt(set1.lower(m),set2.lower(m));
        for (int i : set1) {
            last = set2.pollLast();
            while (i + last >= m && set2.size() > 0) last = set2.pollLast();
            answer = maxInt(answer, (i + last) % m);
            if (set2.size() == 0) break;
        }
        out.print(answer);
    }

    void init() throws FileNotFoundException {
        if (ONLINE_JUDGE) {
            in = new BufferedReader(new InputStreamReader(System.in));
            out = new PrintWriter(System.out);
        } else {
            in = new BufferedReader(new FileReader("input.txt"));
            out = new PrintWriter("output.txt");
        }
        tok = new
                StringTokenizer("");
    }

    int minInt(int... values) {
        int min = Integer.MAX_VALUE;
        for (int value : values) {
            min = Math.min(min, value);
        }
        return min;
    }

    int maxInt(int... values) {
        int max = Integer.MIN_VALUE;
        for (int value : values) {
            max = Math.max(max, value);
        }
        return max;
    }

    long minLong(long... values) {
        long min = Long.MAX_VALUE;
        for (long value : values) {
            min = Math.min(min, value);
        }
        return min;
    }

    long maxLong(long... values) {
        long max = Long.MIN_VALUE;
        for (long value : values) {
            max = Math.max(max, value);
        }
        return max;
    }

    boolean checkIndex(int index, int size) {
        return (0 <= index && index < size);
    }

    int abs(int a) {
        return Math.abs(a);
    }

    int gcd(int a, int b) {
        if (a * b == 0) return maxInt(a, b);
        return gcd(minInt(a, b), maxInt(a, b) % minInt(a, b));
    }

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

    BufferedReader in;
    PrintWriter out;
    StringTokenizer tok;

    void run() {
        try {
            long timeStart = System.currentTimeMillis();

            init();
            solve();

            out.close();

            long timeEnd = System.currentTimeMillis();
            System.err.println("time = " + (timeEnd - timeStart) + " compiled");
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(-1);
        }

    }

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

    String delimiter = " ";

    String readString() throws IOException {
        while (!tok.hasMoreTokens()) {
            String nextLine = readLine();
            if (null == nextLine)
                return null;

            tok = new StringTokenizer(nextLine);
        }

        return tok.nextToken(delimiter);
    }

    int[] readIntArray(int b) {
        int a[] = new int[b];
        for (int i = 0; i < b; i++) {
            try {
                a[i] = readInt();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return a;
    }

    long[] readLongArray(int b) {
        long a[] = new long[b];
        for (int i = 0; i < b; i++) {
            try {
                a[i] = readLong();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return a;
    }

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

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

    void sortArrayInt(int[] a) {
        Integer arr[] = new Integer[a.length];
        for (int i = 0; i < a.length; i++) {
            arr[i] = a[i];
        }
        Arrays.sort(arr);
        for (int i = 0; i < a.length; i++) {
            a[i] = arr[i];
        }
    }

    void sortArrayLong(long[] a) {
        Long arr[] = new Long[a.length];
        for (int i = 0; i < a.length; i++) {
            arr[i] = a[i];
        }
        Arrays.sort(arr);
        for (int i = 0; i < a.length; i++) {
            a[i] = arr[i];
        }
    }

}

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

public class Main {

    void solve() throws IOException {
        int n = readInt();
        int m = readInt();
        int[] a = readIntArray(n);
        HashSet<Integer> set1 = new HashSet<Integer>();
        HashSet<Integer> set2 = new HashSet<Integer>();
        HashSet<Integer> delta = new HashSet<Integer>();
        for (int i = 0; i < n / 2; i++) {
            delta.clear();
            for (int j : set1) delta.add((j + a[i]) % m);
            for (int j : delta) set1.add(j);
            set1.add(a[i]);
        }
        for (int i = n / 2; i < n; i++) {
            delta.clear();
            for (int j : set2) delta.add((j + a[i]) % m);
            for (int j : delta) set2.add(j);
            set2.add(a[i]);
        }

        TreeSet<Integer> s1 = new TreeSet<Integer>();
        TreeSet<Integer> s2 = new TreeSet<Integer>();
        s1.add(0);
        s2.add(0);
        for (int i : set1) s1.add(i);
        for (int i : set2) s2.add(i);
        int answer = 0;
        for (int i : s1) {
            if (s2.lower(m - i) != null) {
                answer = maxInt(answer, i + s2.lower(m - i));
            }
        }
        out.println(answer);
    }

    class SegmentTree {
        int[] t;

        SegmentTree(int[] a, int n) {
            t = new int[4 * n];
            build(a, 1, 1, n);
        }

        void build(int[] a, int v, int tl, int tr) {
            if (tl == tr) {
                t[v] = a[tl];
                return;
            }

            int tm = (tl + tr) / 2;
            build(a, 2 * v, tl, tm);
            build(a, 2 * v + 1, tm + 1, tr);
            t[v] = Math.min(t[2 * v], t[2 * v + 1]);
        }

        void update(int v, int tl, int tr, int pos, int value) {
            if (tl == tr) {
                t[v] = value;
                return;
            }
            int tm = (tl + tr) / 2;
            if (pos <= tm) {
                update(2 * v, tl, tm, pos, value);
            } else {
                update(2 * v + 1, tm + 1, tr, pos, value);
            }

            t[v] = Math.min(t[2 * v], t[2 * v + 1]);
        }

        int getMin(int v, int tl, int tr, int l, int r) {
            if (l > r) {
                return INF;
            }
            if (tl == l && tr == r) {
                return t[v];
            }

            int tm = (tl + tr) / 2;

            int min1 = getMin(2 * v, tl, tm, l, Math.min(tm, r));
            int min2 = getMin(2 * v + 1, tm + 1, tr, Math.max(l, tm + 1), r);

            return Math.min(min1, min2);
        }
    }

    int checkBit(int mask, int bit) {
        return (mask >> bit) & 1;
    }

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

        new Main().run();
    }

    boolean isLower(char a) {
        return ((int) a) >= 97 ? true : false;
    }

    int INF = Integer.MAX_VALUE / 10;

    int[][] STEPS = {{0, 1}, {1, 0}, {-1, 0}, {0, -1}};

    BufferedReader in;
    PrintWriter out;
    StringTokenizer tok;
    Random rnd = new Random();
    static final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;

    Main() throws FileNotFoundException {

        try {
            in = new BufferedReader(new FileReader("input.txt"));
            out = new PrintWriter("output.txt");
        } catch (Exception e) {
            in = new BufferedReader(new InputStreamReader(System.in));
            out = new PrintWriter(System.out);
        }

        tok = new StringTokenizer("");
    }

    long checkBit(long mask, int bit) {
        return (mask >> bit) & 1;
    }

    void run() throws IOException {
        solve();
        out.close();
    }

    char varChar;
    int varInt, varInt1, varInt2;
    long varLong;

    void swapInt(int a, int b) {
        varInt = a;
        a = b;
        b = varInt;
    }

    void swapChar(char a, char b) {
        varChar = a;
        a = b;
        b = varChar;
    }

    void swapLong(long a, long b) {
        varLong = a;
        a = b;
        b = varLong;
    }

    void reverseCharArray(char[] arr) {
        for (int i = 0; i < arr.length; i++) swapChar(arr[i], arr[arr.length - i - 1]);
    }

    int sqrt(double m) {
        varInt1 = 0;
        varInt2 = Integer.MAX_VALUE;
        int i = 1000;
        while (varInt2 >= varInt2) {
            i = (varInt2 + varInt1) / 2;
            if ((long) i * i > m) {
                varInt2 = i - 1;
            } else {
                varInt1 = i + 1;
                varInt = varInt1 - 1;
            }
        }
        return varInt;
    }

    int countPow(int m, int n) {
        varInt = 0;
        while (m % n == 0 && m > 0) {
            varInt++;
            m /= n;
        }
        return varInt;
    }

    long binPow(long a, long b) {
        if (b == 0) {
            return 1;
        }
        if (b % 2 == 1) {
            return a * binPow(a, b - 1);
        } else {
            varLong = binPow(a, b / 2);
            return varLong * varLong;
        }

    }

    int gcd(int a, int b) {
        return b == 0 ? a : gcd(b, a % b);
    }

    long pow(long x, long k) {
        varLong = 1;
        for (int i = 0; i < k; ++i) {
            varLong *= x;
        }
        return varLong;
    }

    class Fenwik {
        private long[] t;
        private int length;

        Fenwik(int[] a) {
            this.length = a.length + 100;
            this.t = new long[length];
            for (int i = 0; i < a.length; ++i) {
                this.inc(i, a[i]);
            }
        }

        void inc(int i, int delta) {
            for (; i < this.length; i = i | (i + 1)) {
                this.t[i] += delta;
            }
        }

        long getSum(int r) {
            long sum = 0;

            for (; r >= 0; r = (r & (r + 1)) - 1) {
                sum += this.t[r];
            }

            return sum;
        }
    }

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

    String delimiter = " ";

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

    String readString() throws IOException {
        while (!tok.hasMoreTokens()) {
            String nextLine = readLine();
            if (null == nextLine)
                return null;

            tok = new StringTokenizer(nextLine);
        }

        return tok.nextToken(delimiter);
    }

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

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

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

    int[] readIntArray(int b) {
        int a[] = new int[b];
        for (int i = 0; i < b; i++) {
            try {
                a[i] = readInt();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return a;
    }

    int[] readSortedIntArray(int size) throws IOException {
        Integer[] array = new Integer[size];

        for (int index = 0; index < size; ++index) {
            array[index] = readInt();
        }
        Arrays.sort(array);

        int[] sortedArray = new int[size];
        for (int index = 0; index < size; ++index) {
            sortedArray[index] = array[index];
        }

        return sortedArray;
    }

    int[] sortedIntArray(int size, int[] array) throws IOException {
        for (int index = 0; index < size; ++index) {
            array[index] = readInt();
        }
        Arrays.sort(array);

        int[] sortedArray = new int[size];
        for (int index = 0; index < size; ++index) {
            sortedArray[index] = array[index];
        }

        return sortedArray;
    }

    int minInt(int... values) {
        int min = Integer.MAX_VALUE;
        for (int value : values) {
            min = Math.min(min, value);
        }
        return min;
    }

    int maxInt(int... values) {
        int max = Integer.MIN_VALUE;
        for (int value : values) {
            max = Math.max(max, value);
        }
        return max;
    }

    long minLong(long... values) {
        long min = Long.MAX_VALUE;
        for (long value : values) {
            min = Math.min(min, value);
        }
        return min;
    }

    long maxLong(long... values) {
        long max = Long.MIN_VALUE;
        for (long value : values) {
            max = Math.max(max, value);
        }
        return max;
    }

    boolean checkIndex(int index, int size) {
        return (0 <= index && index < size);
    }

    int abs(int a) {
        return Math.abs(a);
    }
}

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

public class Main {
    static final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
    static final int[][] STEPS = {{1, 2}, {1, -2}, {-1, 2}, {-1, -2}, {2, 1}, {2, -1}, {-2, 1}, {-2, -1}};

    void solve() throws IOException {
        int n = readInt(), m = readInt();
        int[] a = new int[n];
        for (int i = 0; i < n; i++) {
            a[i] = readInt() % m;
        }
        if (n == 1) {
            out.print(a[0] % m);
            return;
        }
        int n1 = n / 2;
        int n2 = n - n / 2;
        ArrayList<Integer> list1 = new ArrayList<Integer>();
        ArrayList<Integer> list2 = new ArrayList<Integer>();
        ArrayList<Integer> added = new ArrayList<Integer>();
        list1.add(a[0]);
        for (int i = 0; i <= n1; i++) {
            for (int j : list1) {
                added.add((j + a[i]) % m);
            }
            for (int j : added) {
                list1.add(j);
            }
            list1.add(a[i]);
            added.clear();
        }
        added.clear();
        added.add(a[n1]);
        for (int i = n1 + 1; i < n; i++) {
            for (int j : list2) {
                added.add((j + a[i]) % m);
            }
            for (int j : added) {
                list2.add(j);

            }
            list2.add(a[i]);
            added.clear();
        }
        TreeSet<Integer> set1 = new TreeSet<Integer>();
        TreeSet<Integer> set2 = new TreeSet<Integer>();
        for (int i : list1) {
            set1.add(i);
        }
        for (int j : list2) {
            set2.add(j);
        }
        int last = 0;
        int answer = maxInt(list1.get(list1.size() - 1), list2.get(list2.size() - 1));
        for (int i : set1) {
            last = set2.pollLast();
            while (i + last >= m && set2.size() > 0) last = set2.pollLast();
            answer = maxInt(answer, (i + last) % m);
            if (set2.size() == 0) break;
        }
        out.print(answer);
    }

    void init() throws FileNotFoundException {
        if (ONLINE_JUDGE) {
            in = new BufferedReader(new InputStreamReader(System.in));
            out = new PrintWriter(System.out);
        } else {
            in = new BufferedReader(new FileReader("input.txt"));
            out = new PrintWriter("output.txt");
        }
        tok = new
                StringTokenizer("");
    }

    int minInt(int... values) {
        int min = Integer.MAX_VALUE;
        for (int value : values) {
            min = Math.min(min, value);
        }
        return min;
    }

    int maxInt(int... values) {
        int max = Integer.MIN_VALUE;
        for (int value : values) {
            max = Math.max(max, value);
        }
        return max;
    }

    long minLong(long... values) {
        long min = Long.MAX_VALUE;
        for (long value : values) {
            min = Math.min(min, value);
        }
        return min;
    }

    long maxLong(long... values) {
        long max = Long.MIN_VALUE;
        for (long value : values) {
            max = Math.max(max, value);
        }
        return max;
    }

    boolean checkIndex(int index, int size) {
        return (0 <= index && index < size);
    }

    int abs(int a) {
        return Math.abs(a);
    }

    int gcd(int a, int b) {
        if (a * b == 0) return maxInt(a, b);
        return gcd(minInt(a, b), maxInt(a, b) % minInt(a, b));
    }

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

    BufferedReader in;
    PrintWriter out;
    StringTokenizer tok;

    void run() {
        try {
            long timeStart = System.currentTimeMillis();

            init();
            solve();

            out.close();

            long timeEnd = System.currentTimeMillis();
            System.err.println("time = " + (timeEnd - timeStart) + " compiled");
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(-1);
        }

    }

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

    String delimiter = " ";

    String readString() throws IOException {
        while (!tok.hasMoreTokens()) {
            String nextLine = readLine();
            if (null == nextLine)
                return null;

            tok = new StringTokenizer(nextLine);
        }

        return tok.nextToken(delimiter);
    }

    int[] readIntArray(int b) {
        int a[] = new int[b];
        for (int i = 0; i < b; i++) {
            try {
                a[i] = readInt();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return a;
    }

    long[] readLongArray(int b) {
        long a[] = new long[b];
        for (int i = 0; i < b; i++) {
            try {
                a[i] = readLong();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return a;
    }

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

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

    void sortArrayInt(int[] a) {
        Integer arr[] = new Integer[a.length];
        for (int i = 0; i < a.length; i++) {
            arr[i] = a[i];
        }
        Arrays.sort(arr);
        for (int i = 0; i < a.length; i++) {
            a[i] = arr[i];
        }
    }

    void sortArrayLong(long[] a) {
        Long arr[] = new Long[a.length];
        for (int i = 0; i < a.length; i++) {
            arr[i] = a[i];
        }
        Arrays.sort(arr);
        for (int i = 0; i < a.length; i++) {
            a[i] = arr[i];
        }
    }

}

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

public class Main {
    static final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
    static final int[][] STEPS = {{1, 2}, {1, -2}, {-1, 2}, {-1, -2}, {2, 1}, {2, -1}, {-2, 1}, {-2, -1}};

    void solve() throws IOException {
        int n = readInt(), m = readInt();
        int[] a = new int[n];
        for (int i = 0; i < n; i++) {
            a[i] = readInt() % m;
        }
        if (n == 1) {
            out.print(a[0] % m);
            return;
        }
        int n1 = n / 2;
        int n2 = n - n / 2;
        ArrayList<Integer> list1 = new ArrayList<Integer>();
        ArrayList<Integer> list2 = new ArrayList<Integer>();
        ArrayList<Integer> added = new ArrayList<Integer>();
        list1.add(0);
        list1.add(a[0]);
        for (int i = 0; i < n1; i++) {
            for (int j : list1) {
                added.add((j + a[i]) % m);
            }
            for (int j : added) {
                list1.add(j);
            }
        }
        added.clear();
        added.add(0);
        added.add(a[n1]);
        for (int i = n1; i < n; i++) {
            for (int j : list1) {
                added.add((j + a[i]) % m);
            }
            for (int j : added) {
                list2.add(j);
            }
        }
        Collections.sort(list1);
        Collections.sort(list2);
        int flag = list2.size() - 1;
        int answer = maxInt(list1.get(list1.size() - 1), list2.get(list2.size() - 1));
        for (int i : list1) {
            while (i + list2.get(flag) >= m && flag > 0) flag--;
            if (flag < 0) break;
            answer = maxInt(answer, (i + list2.get(flag)) % m);
        }
        out.print(answer);
    }

    void init() throws FileNotFoundException {
        if (ONLINE_JUDGE) {
            in = new BufferedReader(new InputStreamReader(System.in));
            out = new PrintWriter(System.out);
        } else {
            in = new BufferedReader(new FileReader("input.txt"));
            out = new PrintWriter("output.txt");
        }
        tok = new
                StringTokenizer("");
    }

    int minInt(int... values) {
        int min = Integer.MAX_VALUE;
        for (int value : values) {
            min = Math.min(min, value);
        }
        return min;
    }

    int maxInt(int... values) {
        int max = Integer.MIN_VALUE;
        for (int value : values) {
            max = Math.max(max, value);
        }
        return max;
    }

    long minLong(long... values) {
        long min = Long.MAX_VALUE;
        for (long value : values) {
            min = Math.min(min, value);
        }
        return min;
    }

    long maxLong(long... values) {
        long max = Long.MIN_VALUE;
        for (long value : values) {
            max = Math.max(max, value);
        }
        return max;
    }

    boolean checkIndex(int index, int size) {
        return (0 <= index && index < size);
    }

    int abs(int a) {
        return Math.abs(a);
    }

    int gcd(int a, int b) {
        if (a * b == 0) return maxInt(a, b);
        return gcd(minInt(a, b), maxInt(a, b) % minInt(a, b));
    }

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

    BufferedReader in;
    PrintWriter out;
    StringTokenizer tok;

    void run() {
        try {
            long timeStart = System.currentTimeMillis();

            init();
            solve();

            out.close();

            long timeEnd = System.currentTimeMillis();
            System.err.println("time = " + (timeEnd - timeStart) + " compiled");
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(-1);
        }

    }

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

    String delimiter = " ";

    String readString() throws IOException {
        while (!tok.hasMoreTokens()) {
            String nextLine = readLine();
            if (null == nextLine)
                return null;

            tok = new StringTokenizer(nextLine);
        }

        return tok.nextToken(delimiter);
    }

    int[] readIntArray(int b) {
        int a[] = new int[b];
        for (int i = 0; i < b; i++) {
            try {
                a[i] = readInt();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return a;
    }

    long[] readLongArray(int b) {
        long a[] = new long[b];
        for (int i = 0; i < b; i++) {
            try {
                a[i] = readLong();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return a;
    }

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

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

    void sortArrayInt(int[] a) {
        Integer arr[] = new Integer[a.length];
        for (int i = 0; i < a.length; i++) {
            arr[i] = a[i];
        }
        Arrays.sort(arr);
        for (int i = 0; i < a.length; i++) {
            a[i] = arr[i];
        }
    }

    void sortArrayLong(long[] a) {
        Long arr[] = new Long[a.length];
        for (int i = 0; i < a.length; i++) {
            arr[i] = a[i];
        }
        Arrays.sort(arr);
        for (int i = 0; i < a.length; i++) {
            a[i] = arr[i];
        }
    }

}

/**
 * @author prakhar28
 *
 */
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class Main{

	static class Reader
    {
        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(String file_name) throws IOException
        {
            din = new DataInputStream(new FileInputStream(file_name));
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }

        public String readLine() throws IOException
        {
            byte[] buf = new byte[200005]; // line length+1
            int cnt = 0, c;
            while ((c = read()) != -1)
            {
                if (c == '\n')
                    break;
                buf[cnt++] = (byte) c;
            }
            return new String(buf, 0, cnt);
        }

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

	static class FastScanner {

	    private final BufferedReader bufferedReader;
	    private StringTokenizer stringTokenizer;

	    public FastScanner() {
	        bufferedReader = new BufferedReader(new InputStreamReader(System.in));
	    }

	    public String next() {
	        while (stringTokenizer == null || !stringTokenizer.hasMoreElements()) {
	            try {
	                stringTokenizer = new StringTokenizer(bufferedReader.readLine());
	            } catch (IOException e) {
	                throw new RuntimeException("Can't read next value", e);
	            }
	        }
	        return stringTokenizer.nextToken();
	    }

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

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

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

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

	static void closeall() throws IOException{
		printWriter.close();
		sc.close();
		in.close();
	}
	static Scanner sc = new Scanner(System.in);
	static Reader in = new Reader();
	static FastScanner fastScanner = new FastScanner();
	static PrintWriter printWriter = new PrintWriter(new BufferedOutputStream(System.out));
	static BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
	static long INF = (long)(1e18);

	int V,E;
	ArrayList<Integer> adj[];
	ArrayList<Integer> path;
	Main(){
	}
	Main(int v,int e){
		V=v;
		E=e;
		adj=new ArrayList[v];
		path = new ArrayList<>();
		for(int i=0;i<v;i++)
			adj[i] = new ArrayList<>();
	}
	void addEdge(int u,int v){
		adj[u].add(v);
		adj[v].add(u);
	}

	static long power(long a,long k)
	{
		long m = 1000000007;
	    long ans=1;
	    long tmp=a%m;
	    while(k>0)
	    {
	        if(k%2==1)
	        	ans=ans*tmp%m;
	        tmp=tmp*tmp%m;
	        k>>=1;
	    }
	    return ans;
	}

	static class Pair implements Comparable<Pair>{
		int num,index;
		Pair(int x,int y){
			num = x;
			index = y;
		}
		public int compareTo(Pair ob){
			return this.num-ob.num;
		}

	}
	static int gcd(int a,int b) {
		if(a<b) {
			int t = a;
			a = b;
			b = t;
		}
		int r = a%b;
		if(r==0)
			return b;
		return gcd(b,r);
	}

	static int lower_bound(int[] a,int low,int high,int val) {
		while(low!=high) {
			int mid = (low+high)/2;
			if(a[mid]<val)
				low=mid+1;
			else
				high=mid;
		}
		return low;
	}

	static long mod = 1000000007;
	public static void main(String args[])throws IOException{
		Reader in = new Reader();
		int n = in.nextInt();
		int mod = in.nextInt();
		int[] a = new int[n];
		for(int i=0;i<n;i++) {
			a[i] = in.nextInt();
			a[i]=a[i]%mod;
		}
		int p[] = new int[300000];
		int q[] = new int[300000];
		int tp=-1,tq=-1;
		Arrays.fill(p, Integer.MAX_VALUE);
		Arrays.fill(q, Integer.MAX_VALUE);
		int mid = n/2;
		int total = 1<<mid;
		for(int i=0;i<total;i++) {
			int s = 0;
			for(int j=0;j<mid;j++) {
				if((i&(1<<j))!=0)
					s=(s%mod+a[j]%mod)%mod;
			}
			p[++tp]=s;
		}
		mid = n-mid;
		total = 1<<mid;
		for(int i=0;i<total;i++) {
			int s = 0;
			for(int j=n/2;j<n;j++) {
				if((i&(1<<(j-n/2)))!=0)
					s=(s%mod+a[j]%mod)%mod;
			}
			q[++tq]=s;
		}
		/*for(int i=0;i<=tp;i++)
			printWriter.print(p[i]+" ");
		printWriter.println();
		for(int i=0;i<=tq;i++)
			printWriter.print(q[i]+" ");*/
		Arrays.sort(p);
		Arrays.sort(q);
		int ans=(int)Math.max(p[tp], q[tq]);
		for(int i=0;i<=tp;i++) {
			int idx1 = lower_bound(q,0,tq,mod-p[i]);
			int idx2 = lower_bound(q,0,tq,2*mod-p[i]);
			idx1--;
			idx2--;
			if(idx1>=0)
				ans=(int)Math.max(ans, p[i]+q[idx1]);
			if(idx2>=0)
				ans=(int)Math.max(ans, (p[i]%mod+q[idx2]%mod)%mod);
		}
		printWriter.println(ans);
		closeall();
	}
}

/**
 * @author prakhar28
 *
 */
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class Main{

	static class Reader
    {
        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(String file_name) throws IOException
        {
            din = new DataInputStream(new FileInputStream(file_name));
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }

        public String readLine() throws IOException
        {
            byte[] buf = new byte[200005]; // line length+1
            int cnt = 0, c;
            while ((c = read()) != -1)
            {
                if (c == '\n')
                    break;
                buf[cnt++] = (byte) c;
            }
            return new String(buf, 0, cnt);
        }

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

	static class FastScanner {

	    private final BufferedReader bufferedReader;
	    private StringTokenizer stringTokenizer;

	    public FastScanner() {
	        bufferedReader = new BufferedReader(new InputStreamReader(System.in));
	    }

	    public String next() {
	        while (stringTokenizer == null || !stringTokenizer.hasMoreElements()) {
	            try {
	                stringTokenizer = new StringTokenizer(bufferedReader.readLine());
	            } catch (IOException e) {
	                throw new RuntimeException("Can't read next value", e);
	            }
	        }
	        return stringTokenizer.nextToken();
	    }

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

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

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

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

	static void closeall() throws IOException{
		printWriter.close();
		sc.close();
		in.close();
	}
	static Scanner sc = new Scanner(System.in);
	static Reader in = new Reader();
	static FastScanner fastScanner = new FastScanner();
	static PrintWriter printWriter = new PrintWriter(new BufferedOutputStream(System.out));
	static BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
	static long INF = (long)(1e18);

	int V,E;
	ArrayList<Integer> adj[];
	ArrayList<Integer> path;
	Main(){
	}
	Main(int v,int e){
		V=v;
		E=e;
		adj=new ArrayList[v];
		path = new ArrayList<>();
		for(int i=0;i<v;i++)
			adj[i] = new ArrayList<>();
	}
	void addEdge(int u,int v){
		adj[u].add(v);
		adj[v].add(u);
	}

	static long power(long a,long k)
	{
		long m = 1000000007;
	    long ans=1;
	    long tmp=a%m;
	    while(k>0)
	    {
	        if(k%2==1)
	        	ans=ans*tmp%m;
	        tmp=tmp*tmp%m;
	        k>>=1;
	    }
	    return ans;
	}

	static class Pair implements Comparable<Pair>{
		int num,index;
		Pair(int x,int y){
			num = x;
			index = y;
		}
		public int compareTo(Pair ob){
			return this.num-ob.num;
		}

	}
	static int gcd(int a,int b) {
		if(a<b) {
			int t = a;
			a = b;
			b = t;
		}
		int r = a%b;
		if(r==0)
			return b;
		return gcd(b,r);
	}

	static long mod = 1000000007;
	public static void main(String args[])throws IOException{
		Reader in = new Reader();
		int n = in.nextInt();
		int m = in.nextInt();
		int[] a = new int[n];
		for(int i=0;i<n;i++) {
			a[i] = in.nextInt();
			a[i]%=m;
		}
		int[] dp = new int[n];
		Arrays.fill(dp, -1);
		printWriter.println(m-1-get(dp,m-1,a,0,n-1));
		closeall();
	}
	static int get(int[] dp,int s,int[] a,int prv,int i) {
		if(i<0)
			return s;
		if(dp[i]==-1) {
			if(s==0)
				dp[i] = s;
			else if(s<0)
				dp[i] = s+prv;
			else
				dp[i] = (int)Math.min(get(dp,s-a[i],a,a[i],i-1), get(dp,s,a,0,i-1));
		}
		return dp[i];
	}
}

/**
 * @author prakhar28
 *
 */
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class Main{

	static class Reader
    {
        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(String file_name) throws IOException
        {
            din = new DataInputStream(new FileInputStream(file_name));
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }

        public String readLine() throws IOException
        {
            byte[] buf = new byte[200005]; // line length+1
            int cnt = 0, c;
            while ((c = read()) != -1)
            {
                if (c == '\n')
                    break;
                buf[cnt++] = (byte) c;
            }
            return new String(buf, 0, cnt);
        }

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

	static class FastScanner {

	    private final BufferedReader bufferedReader;
	    private StringTokenizer stringTokenizer;

	    public FastScanner() {
	        bufferedReader = new BufferedReader(new InputStreamReader(System.in));
	    }

	    public String next() {
	        while (stringTokenizer == null || !stringTokenizer.hasMoreElements()) {
	            try {
	                stringTokenizer = new StringTokenizer(bufferedReader.readLine());
	            } catch (IOException e) {
	                throw new RuntimeException("Can't read next value", e);
	            }
	        }
	        return stringTokenizer.nextToken();
	    }

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

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

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

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

	static void closeall() throws IOException{
		printWriter.close();
		sc.close();
		in.close();
	}
	static Scanner sc = new Scanner(System.in);
	static Reader in = new Reader();
	static FastScanner fastScanner = new FastScanner();
	static PrintWriter printWriter = new PrintWriter(new BufferedOutputStream(System.out));
	static BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
	static long INF = (long)(1e18);

	int V,E;
	ArrayList<Integer> adj[];
	ArrayList<Integer> path;
	Main(){
	}
	Main(int v,int e){
		V=v;
		E=e;
		adj=new ArrayList[v];
		path = new ArrayList<>();
		for(int i=0;i<v;i++)
			adj[i] = new ArrayList<>();
	}
	void addEdge(int u,int v){
		adj[u].add(v);
		adj[v].add(u);
	}

	static long power(long a,long k)
	{
		long m = 1000000007;
	    long ans=1;
	    long tmp=a%m;
	    while(k>0)
	    {
	        if(k%2==1)
	        	ans=ans*tmp%m;
	        tmp=tmp*tmp%m;
	        k>>=1;
	    }
	    return ans;
	}

	static class Pair implements Comparable<Pair>{
		int num,index;
		Pair(int x,int y){
			num = x;
			index = y;
		}
		public int compareTo(Pair ob){
			return this.num-ob.num;
		}

	}
	static int gcd(int a,int b) {
		if(a<b) {
			int t = a;
			a = b;
			b = t;
		}
		int r = a%b;
		if(r==0)
			return b;
		return gcd(b,r);
	}

	static int lower_bound(int[] a,int low,int high,int val) {
		while(low!=high) {
			int mid = (low+high)/2;
			if(a[mid]<val)
				low=mid+1;
			else
				high=mid;
		}
		return low;
	}

	static long mod = 1000000007;
	public static void main(String args[])throws IOException{
		Reader in = new Reader();
		int n = in.nextInt();
		int mod = in.nextInt();
		int[] a = new int[n];
		for(int i=0;i<n;i++) {
			a[i] = in.nextInt();
			a[i]=a[i]%mod;
		}
		int p[] = new int[300000];
		int q[] = new int[300000];
		int tp=-1,tq=-1;
		Arrays.fill(p, Integer.MAX_VALUE);
		Arrays.fill(q, Integer.MAX_VALUE);
		int mid = n/2;
		int total = 1<<mid;
		for(int i=0;i<total;i++) {
			int s = 0;
			for(int j=0;j<mid;j++) {
				if((i&(1<<j))!=0)
					s=(s%mod+a[j]%mod)%mod;
			}
			p[++tp]=s;
		}
		mid = n-mid;
		total = 1<<mid;
		for(int i=0;i<total;i++) {
			int s = 0;
			for(int j=n/2;j<n;j++) {
				if((i&(1<<(j-n/2)))!=0)
					s=(s%mod+a[j]%mod)%mod;
			}
			q[++tq]=s;
		}
		/*for(int i=0;i<=tp;i++)
			printWriter.print(p[i]+" ");
		printWriter.println();
		for(int i=0;i<=tq;i++)
			printWriter.print(q[i]+" ");*/
		Arrays.sort(p);
		Arrays.sort(q);
		int ans=(int)Math.max(p[tp], q[tq]);
		for(int i=0;i<=tp;i++) {
			int idx1 = lower_bound(q,0,tq,mod-p[i]);
			int idx2 = lower_bound(q,0,tq,2*mod-p[i]);
			idx1--;
			idx2--;
			if(idx1>=0)
				ans=(int)Math.max(ans, (p[i]+q[idx1])%mod);
			if(idx2>=0)
				ans=(int)Math.max(ans, (p[i]%mod+q[idx2]%mod)%mod);
		}
		printWriter.println(ans);
		closeall();
	}
}

import java.math.BigInteger;
import java.text.DecimalFormat;
import java.util.*;
import java.io.*;

public class Main {
    private static int [] A ;
    private static int n;

    public static void main(String[] args) throws Exception {
        IO io ;
        try {
            io = new IO("in.in", null);
        } catch (IOException e) {
            io = new IO(null, null);
        }
        n = io.getNextInt();
        int mod = io.getNextInt();
        A = new int[n];
        for (int i = 0;i < n;i++)
            A[i] = io.getNextInt();

        int m = n/2,ans = 0;
        ArrayList<Integer> AS = new ArrayList<>(1 << m);
        for (int msk = 0;msk < (1 << m);msk++) {
            int s = 0;
            for (int i = 0;i < m;i++) {
                int v = A[i];
                if ((msk & (1 << i)) != 0)
                    s = (s + v)%mod;
                if (s > ans) ans = s;
                AS.add(s);
            }
        }
        Collections.sort(AS);
        ArrayList<Integer> AS2 = new ArrayList<>(1 << (n-m));
        int j = -1;
        for (int msk = 0,L = n - m;msk < (1 << L);msk++) {
            int s = 0;
            for (int i = 0;i < L;i++) {
                int v = A[i+m];
                if ((msk & (1 << i)) != 0)
                    s = (s + v)%mod;
                if (s > ans) ans = s;
                AS2.add(s);
            }
        }
        Collections.sort(AS2);
        for (int s : AS2) {
            int target = mod - 1 - s;
            while (j+1 < AS.size() && AS.get(j+1) <= target)
                j++;
            if (j != -1) {
                int tmp = (s + AS.get(j))%mod;
                if (tmp > ans)
                    ans = tmp;
            }
        }
        io.println(ans);
        io.close();
    }
    private static final int onebillion7 = 1000000007;
}

class IO{
    private BufferedReader br;
    private StringTokenizer st;
    private PrintWriter writer;
    private String inputFile,outputFile;

    public boolean hasMore() throws IOException{
        if(st != null && st.hasMoreTokens()) return true;
        if(br != null && br.ready()) return true;
        return false;
    }

    public String getNext() throws FileNotFoundException, IOException{
        while(st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine());
        return st.nextToken();
    }

    public String getNextLine() throws FileNotFoundException, IOException{
        return br.readLine().trim();
    }

    public int getNextInt() throws FileNotFoundException, IOException{
        return Integer.parseInt(getNext());
    }
    public long getNextLong() throws FileNotFoundException, IOException{
        return Long.parseLong(getNext());
    }

    public void print(double x,int num_digits) throws  IOException{
        writer.printf("%." + num_digits + "f" ,x);
    }
    public void println(double x,int num_digits) throws  IOException{
        writer.printf("%." + num_digits + "f\n" ,x);
    }
    public void print(Object o) throws  IOException{
        writer.print(o.toString());
    }

    public void println(Object o) throws  IOException{
        writer.println(o.toString());
    }
    public IO(String x,String y) throws FileNotFoundException, IOException{
        inputFile = x;
        outputFile = y;
        if(x != null) br = new BufferedReader(new FileReader(inputFile));
        else br = new BufferedReader(new InputStreamReader(System.in));
        if(y != null) writer = new PrintWriter(new BufferedWriter(new FileWriter(outputFile)));
        else writer = new PrintWriter(new OutputStreamWriter(System.out));
    }

    protected void close() throws IOException{
        br.close();
        writer.close();
    }
    public void outputArr(Object [] A) throws IOException{
        int L = A.length;
        for (int i = 0;i < L;i++) {
            if(i > 0) writer.print(" ");
            writer.print(A[i]);
        }
        writer.print("\n");
    }
}

/**
 * DA-IICT
 * Author : Savaliya Sagar
 */
import java.io.*;
import java.math.*;
import java.util.*;

import static java.util.Arrays.fill;
import static java.lang.Math.*;
import static java.util.Arrays.sort;
import static java.util.Collections.sort;

public class E888
{
	InputStream is;
	PrintWriter out;
	String INPUT = "";

	void solve()
	{
		int n = ni();
		int m = ni();
		int a[] = na(n);
		ArrayList<Integer> l = new ArrayList<>();
		ArrayList<Integer> r = new ArrayList<>();
		int le = n/2;
		int re = n - n/2;
		for(int i=0;i<(1<<le);i++) {
			long sum = 0;
			for(int j=0;j<le;j++) {
				if(((i>>j)&1)==1)
					sum += a[j];
			}
			l.add((int)sum%m);
		}
		for(int i=0;i<(1<<re);i++) {
			long sum = 0;
			for(int j=0;j<re;j++) {
				if(((i>>j)&1)==1)
					sum += a[le+j];
			}
			r.add((int)sum%m);
		}
		sort(r);
		long ans = 0;
		for(int i=0;i<l.size();i++) {
			long  t = l.get(i) + bs(r,m-1-l.get(i));
			ans = max(ans,t%m);
		}
		out.println(ans);
	}
	int bs(ArrayList<Integer> a,int k) {
		int l =0;
		int r = a.size()-1;
		int ans = 0;
		while(l<=r) {
			int mid = (l+r)/2;
			if(a.get(mid)<=k)
			{
				ans = a.get(mid);
				l = mid+1;
			}else
				r = mid - 1;
		}
		return ans;
	}
	private int[] na(int n)
	{
		int[] a = new int[n];
		for (int i = 0; i < n; i++)
			a[i] = ni();
		return a;
	}
	void run() throws Exception
	{
		is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
		out = new PrintWriter(System.out);

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

	public static void main(String[] args) throws Exception
	{
		new Thread(null, new Runnable()
		{
			public void run()
			{
				try
				{
					new E888().run();
				} catch (Exception e)
				{
					e.printStackTrace();
				}
			}
		}, "1", 1 << 26).start();
	}

	private byte[] inbuf = new byte[1024];
	public int lenbuf = 0, ptrbuf = 0;

	private int readByte()
	{
		if (lenbuf == -1)
			throw new InputMismatchException();
		if (ptrbuf >= lenbuf)
		{
			ptrbuf = 0;
			try
			{
				lenbuf = is.read(inbuf);
			} catch (IOException e)
			{
				throw new InputMismatchException();
			}
			if (lenbuf <= 0)
				return -1;
		}
		return inbuf[ptrbuf++];
	}

	private boolean isSpaceChar(int c)
	{
		return !(c >= 33 && c <= 126);
	}

	private int skip()
	{
		int b;
		while ((b = readByte()) != -1 && isSpaceChar(b))
			;
		return b;
	}

	private double nd()
	{
		return Double.parseDouble(ns());
	}

	private char nc()
	{
		return (char) skip();
	}

	private String ns()
	{
		int b = skip();
		StringBuilder sb = new StringBuilder();
		while (!(isSpaceChar(b)))
		{ // when nextLine, (isSpaceChar(b) && b !=
			// ' ')
			sb.appendCodePoint(b);
			b = readByte();
		}
		return sb.toString();
	}

	private char[] ns(int n)
	{
		char[] buf = new char[n];
		int b = skip(), p = 0;
		while (p < n && !(isSpaceChar(b)))
		{
			buf[p++] = (char) b;
			b = readByte();
		}
		return n == p ? buf : Arrays.copyOf(buf, p);
	}

	private char[][] nm(int n, int m)
	{
		char[][] map = new char[n][];
		for (int i = 0; i < n; i++)
			map[i] = ns(m);
		return map;
	}

	private int ni()
	{
		int num = 0, b;
		boolean minus = false;
		while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
			;
		if (b == '-')
		{
			minus = true;
			b = readByte();
		}

		while (true)
		{
			if (b >= '0' && b <= '9')
			{
				num = num * 10 + (b - '0');
			} else
			{
				return minus ? -num : num;
			}
			b = readByte();
		}
	}

	private long nl()
	{
		long num = 0;
		int b;
		boolean minus = false;
		while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
			;
		if (b == '-')
		{
			minus = true;
			b = readByte();
		}

		while (true)
		{
			if (b >= '0' && b <= '9')
			{
				num = num * 10 + (b - '0');
			} else
			{
				return minus ? -num : num;
			}
			b = readByte();
		}
	}

	private void tr(Object... o)
	{
		System.out.println(Arrays.deepToString(o));
	}
}

/**
 * DA-IICT
 * Author : Savaliya Sagar
 */
import java.io.*;
import java.math.*;
import java.util.*;

import static java.util.Arrays.fill;
import static java.lang.Math.*;
import static java.util.Arrays.sort;
import static java.util.Collections.sort;

public class E888
{
	InputStream is;
	PrintWriter out;
	String INPUT = "";

	void solve()
	{
		int n = ni();
		int m = ni();
		int a[] = na(n);
		ArrayList<Integer> l = new ArrayList<>();
		ArrayList<Integer> r = new ArrayList<>();
		int le = n/2;
		int re = n - n/2;
		for(int i=0;i<(1<<le);i++) {
			long sum = 0;
			for(int j=0;j<le;j++) {
				if(((i>>j)&1)==1)
					sum += a[j];
			}
			l.add((int)sum%m);
		}
		for(int i=0;i<(1<<re);i++) {
			long sum = 0;
			for(int j=0;j<re;j++) {
				if(((i>>j)&1)==1)
					sum += a[le+j];
			}
			r.add((int)sum%m);
		}
		sort(r);
		long ans = 0;
		for(int i=0;i<l.size();i++) {
			long  t = l.get(i) + bs(r,m-1-l.get(i));
			ans = max(ans,t%m);
		}
		out.println(ans);
	}
	long bs(ArrayList<Integer> a,int k) {
		int l =0;
		int r = a.size()-1;
		long ans = 0;
		while(l<=r) {
			int mid = (l+r)/2;
			if(a.get(mid)<=k)
			{
				ans = a.get(mid);
				l = mid+1;
			}else
				r = mid - 1;
		}
		return ans;
	}
	private int[] na(int n)
	{
		int[] a = new int[n];
		for (int i = 0; i < n; i++)
			a[i] = ni();
		return a;
	}
	void run() throws Exception
	{
		is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
		out = new PrintWriter(System.out);

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

	public static void main(String[] args) throws Exception
	{
		new Thread(null, new Runnable()
		{
			public void run()
			{
				try
				{
					new E888().run();
				} catch (Exception e)
				{
					e.printStackTrace();
				}
			}
		}, "1", 1 << 26).start();
	}

	private byte[] inbuf = new byte[1024];
	public int lenbuf = 0, ptrbuf = 0;

	private int readByte()
	{
		if (lenbuf == -1)
			throw new InputMismatchException();
		if (ptrbuf >= lenbuf)
		{
			ptrbuf = 0;
			try
			{
				lenbuf = is.read(inbuf);
			} catch (IOException e)
			{
				throw new InputMismatchException();
			}
			if (lenbuf <= 0)
				return -1;
		}
		return inbuf[ptrbuf++];
	}

	private boolean isSpaceChar(int c)
	{
		return !(c >= 33 && c <= 126);
	}

	private int skip()
	{
		int b;
		while ((b = readByte()) != -1 && isSpaceChar(b))
			;
		return b;
	}

	private double nd()
	{
		return Double.parseDouble(ns());
	}

	private char nc()
	{
		return (char) skip();
	}

	private String ns()
	{
		int b = skip();
		StringBuilder sb = new StringBuilder();
		while (!(isSpaceChar(b)))
		{ // when nextLine, (isSpaceChar(b) && b !=
			// ' ')
			sb.appendCodePoint(b);
			b = readByte();
		}
		return sb.toString();
	}

	private char[] ns(int n)
	{
		char[] buf = new char[n];
		int b = skip(), p = 0;
		while (p < n && !(isSpaceChar(b)))
		{
			buf[p++] = (char) b;
			b = readByte();
		}
		return n == p ? buf : Arrays.copyOf(buf, p);
	}

	private char[][] nm(int n, int m)
	{
		char[][] map = new char[n][];
		for (int i = 0; i < n; i++)
			map[i] = ns(m);
		return map;
	}

	private int ni()
	{
		int num = 0, b;
		boolean minus = false;
		while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
			;
		if (b == '-')
		{
			minus = true;
			b = readByte();
		}

		while (true)
		{
			if (b >= '0' && b <= '9')
			{
				num = num * 10 + (b - '0');
			} else
			{
				return minus ? -num : num;
			}
			b = readByte();
		}
	}

	private long nl()
	{
		long num = 0;
		int b;
		boolean minus = false;
		while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
			;
		if (b == '-')
		{
			minus = true;
			b = readByte();
		}

		while (true)
		{
			if (b >= '0' && b <= '9')
			{
				num = num * 10 + (b - '0');
			} else
			{
				return minus ? -num : num;
			}
			b = readByte();
		}
	}

	private void tr(Object... o)
	{
		System.out.println(Arrays.deepToString(o));
	}
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;

import static java.lang.Long.bitCount;

public class Main {

    public static void main(String[] args) {
        FastScanner in = new FastScanner();
        int N, M;
        N = in.nextInt();
        M = in.nextInt();
        int []a = new int[N/2];
        int []b = new int[N-N/2];
        for(int i=0; i<N/2; ++i) a[i] = in.nextInt();
        for(int i=0; i<(N-N/2); ++i) b[i] = in.nextInt();

        int []c = new int[(1<<(N/2))];
        int []d = new int[(1<<(N-N/2))];

        for(int i=0; i<(1<<(N/2)); ++i){
            int l = 0;
            for(int j=0; j<N/2; ++j){
                if((i&(1<<j)) != 0){
                    l += a[j];
                }
            }
            c[i] = l%M;
        }

        TreeSet<Integer> ar = new TreeSet<Integer>();
        for(int x: c){
            ar.add(x);
        }
        int []e = new int[ar.size()];
        int t = 0;
        for(int x: ar){
            e[t] = x;
            ++t;
        }

        for(int i=0; i<(1<<(N-N/2)); ++i){
            int l = 0;
            for(int j=0; j<(N-N/2); ++j){
                if((i&(1<<j)) != 0){
                    l += b[j];
                }
            }
            d[i] = l%M;
        }

        TreeSet<Integer> ar2 = new TreeSet<Integer>();
        for(int x: d){
            ar2.add(x);
        }
        int []f = new int[ar2.size()];
        t = 0;
        for(int x: ar2){
            f[t] = x;
            ++t;
        }

        int MAX_ANS = 0;
        int s1 = e.length, s2 = f.length;

        for (int value : e) {
            int v1 = M - value;
            int v2 = (M * 2) - value;
            try{
                int got = ar2.lower(v1);
                int ans = (got+value)%M;
                MAX_ANS = Math.max(MAX_ANS, ans);
            }
            catch (Exception r) {
                System.out.println(0);
                System.exit(0);
            }
            try{
                int got = ar2.lower(v2);
                int ans = (got+value)%M;
                MAX_ANS = Math.max(MAX_ANS, ans);
            }
            catch (Exception r) {
                System.out.println(0);
                System.exit(0);
            }
        }

        System.out.println(MAX_ANS);
    }

    static void sort(int[] a) {
        ArrayList<Integer> l=new ArrayList<>();
        for (int i:a) l.add(i);
        Collections.sort(l);
        for (int i=0; i<a.length; i++) a[i]=l.get(i);
    }

    static class FastScanner {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st=new StringTokenizer("");
        String next() {
            while (!st.hasMoreTokens())
                try {
                    st=new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            return st.nextToken();
        }

        int nextInt() {
            return Integer.parseInt(next());
        }
        int[] readArray(int n) {
            int[] a=new int[n];
            for (int i=0; i<n; i++) a[i]=nextInt();
            return a;
        }
        long nextLong() {
            return Long.parseLong(next());
        }

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

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;

import static java.lang.Long.bitCount;

public class Main {

    public static void main(String[] args) {
        FastScanner in = new FastScanner();
        int N;
        long M;
        N = in.nextInt();
        M = in.nextInt();
        long []a = new long[N/2];
        long []b = new long[N-N/2];
        for(int i=0; i<N/2; ++i) a[i] = in.nextInt();
        for(int i=0; i<(N-N/2); ++i) b[i] = in.nextInt();

        long []c = new long[(1<<(N/2))];
        long []d = new long[(1<<(N-N/2))];

        for(int i=0; i<(1<<(N/2)); ++i){
            long l = 0;
            for(int j=0; j<N/2; ++j){
                if((i&(1<<j)) != 0){
                    l += a[j];
                }
            }
            c[i] = l%M;
        }

        TreeSet<Long> ar = new TreeSet<Long>();
        for(long x: c){
            ar.add(x%M);
        }
        Long []e = new Long[ar.size()];
        int t = 0;
        for(long x: ar){
            e[t] = x;
            ++t;
        }

        for(int i=0; i<(1<<(N-N/2)); ++i){
            long l = 0;
            for(int j=0; j<(N-N/2); ++j){
                if((i&(1<<j)) != 0){
                    l += b[j];
                }
            }
            d[i] = l%M;
        }

        TreeSet<Long> ar2 = new TreeSet<Long>();
        for(long x: d){
            ar2.add(x%M);
        }
        Long []f = new Long[ar2.size()];
        t = 0;
        for(long x: ar2){
            f[t] = x;
            ++t;
        }
/*
        for(long x: e) System.out.print(x+" ");
        System.out.println();
        for(long x: f) System.out.print(x+" ");
        System.out.println();*/

        long MAX_ANS = 0;
        long s1 = e.length, s2 = f.length;

        for (long value : e) {
            long v1 = (M - value)%M;
            long v2 = ((M * 2) - value) % M;
            if(v1==0 && v2==0) continue;
            try{
                long got = ar2.lower(v1);
                long ans = (got+value)%M;
                MAX_ANS = Math.max(MAX_ANS, ans);
            }
            catch (Exception r) {
                System.out.println(0);
                System.exit(0);
            }
            try{
                long got = ar2.lower(v2);
                long ans = (got+value)%M;
                MAX_ANS = Math.max(MAX_ANS, ans);
            }
            catch (Exception r) {
                System.out.println(0);
                System.exit(0);
            }
        }

        System.out.println(MAX_ANS);
    }

    static void sort(int[] a) {
        ArrayList<Integer> l=new ArrayList<>();
        for (int i:a) l.add(i);
        Collections.sort(l);
        for (int i=0; i<a.length; i++) a[i]=l.get(i);
    }

    static class FastScanner {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st=new StringTokenizer("");
        String next() {
            while (!st.hasMoreTokens())
                try {
                    st=new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            return st.nextToken();
        }

        int nextInt() {
            return Integer.parseInt(next());
        }
        int[] readArray(int n) {
            int[] a=new int[n];
            for (int i=0; i<n; i++) a[i]=nextInt();
            return a;
        }
        long nextLong() {
            return Long.parseLong(next());
        }

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

import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.StringTokenizer;

public class E {

	public static long solve_naive(int n, long[] as, long m){
		long ret = 0;

		for(int bit = 0; bit < (1 << n); bit++){
			long curr = 0;

			for(int i = 0; i < n; i++){
				if((bit & (1 << i)) == 0){ continue; }

				curr += as[i];
				curr %= m;
			}

			ret = Math.max(ret, curr);
		}

		return ret;
	}

	public static  ArrayList<HashSet<Long>> solve_smart(int begin, int end, long[] as, long m){
		final int n = end - begin;

		ArrayList<HashSet<Long>> ret = new ArrayList<HashSet<Long>>();
		for(int i = 0; i <= n; i++){ ret.add(new HashSet<Long>()); }

		for(int bit = 0; bit < (1 << n); bit++){
			final int bit_count = Integer.bitCount(bit);

			long curr = 0;
			for(int i = 0; i < n; i++){
				final int index = begin + i;
				if((bit & (1 << index)) == 0){ continue; }

				curr += as[index];
				curr %= m;
			}

			ret.get(bit_count).add(curr);
		}

		return ret;
	}

	public static void main(String[] args) {
		try (final Scanner sc = new Scanner(System.in)) {
			final int n = sc.nextInt();
			final int m = sc.nextInt();

			long[] as = new long[n];
			for(int i = 0; i < n; i++){
				as[i] = sc.nextLong() % m;
			}

			//System.out.println(solve_naive(n, as, m));

			final int fst_size = n / 2;
			final int snd_size = n - n / 2;

			//System.out.println(0 + " " + fst_size + " , " + fst_size + " " + snd_size) ;
			ArrayList<HashSet<Long>> fst_part = solve_smart(0, fst_size, as, m);
			ArrayList<HashSet<Long>> snd_part = solve_smart(fst_size, n, as, m);

			long max = 0;
			for(int fst_count = 0; fst_count <= fst_size; fst_count++){
				for(final long fst_value : fst_part.get(fst_count)){

					for(int snd_count = 0; snd_count <= snd_size; snd_count++){
						for(final long snd_value : snd_part.get(snd_count)){
							max = Math.max(max, (fst_value + snd_value) % m);
						}
					}
				}
			}

			System.out.println(max);
		}
	}

	public static class Scanner implements Closeable {
		private BufferedReader br;
		private StringTokenizer tok;

		public Scanner(InputStream is) {
			br = new BufferedReader(new InputStreamReader(is));
		}

		private void getLine() {
			try {
				while (!hasNext()) {
					tok = new StringTokenizer(br.readLine());
				}
			} catch (IOException e) { /* ignore */
			}
		}

		private boolean hasNext() {
			return tok != null && tok.hasMoreTokens();
		}

		public String next() {
			getLine();
			return tok.nextToken();
		}

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

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

		public void close() {
			try {
				br.close();
			} catch (IOException e) { /* ignore */
			}
		}
	}
}

import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.StringTokenizer;
import java.util.TreeSet;

public class E {

	public static long solve_naive(int n, long[] as, long m){
		long ret = 0;

		for(int bit = 0; bit < (1 << n); bit++){
			long curr = 0;

			for(int i = 0; i < n; i++){
				if((bit & (1 << i)) == 0){ continue; }

				curr += as[i];
				curr %= m;
			}

			ret = Math.max(ret, curr);
		}

		return ret;
	}

	public static  ArrayList<Long> solve_smart(int begin, int end, long[] as, long m){
		final int n = end - begin;

		TreeSet<Long> ret = new TreeSet<Long>();

		for(int bit = 0; bit < (1 << n); bit++){

			long curr = 0;
			for(int i = 0; i < n; i++){
				final int index = begin + i;
				if((bit & (1 << index)) == 0){ continue; }

				curr += as[index];
				curr %= m;
			}

			ret.add(curr);
		}

		return new ArrayList<Long>(ret);
	}

	public static void main(String[] args) {
		try (final Scanner sc = new Scanner(System.in)) {
			final int n = sc.nextInt();
			final int m = sc.nextInt();

			long[] as = new long[n];
			for(int i = 0; i < n; i++){
				as[i] = sc.nextLong() % m;
			}

			//System.out.println(solve_naive(n, as, m));

			final int fst_size = n / 2;
			final int snd_size = n - n / 2;

			//System.out.println(0 + " " + fst_size + " , " + fst_size + " " + snd_size) ;
			ArrayList<Long> fst_part = solve_smart(0, fst_size, as, m);
			ArrayList<Long> snd_part = solve_smart(fst_size, n, as, m);

			long max = 0;
			for(final long fst_value : fst_part){
				final long pur = (m - 1) - fst_value;

				int index = Collections.binarySearch(snd_part, pur);
				if(index >= 0){
					max = Math.max(max, (fst_value + snd_part.get(index)) % m);
				}else{
					index = -(index + 2);
					if(index < 0){ continue; }

					max = Math.max(max, (fst_value + snd_part.get(index)) % m);
				}
			}

			System.out.println(max);
		}
	}

	public static class Scanner implements Closeable {
		private BufferedReader br;
		private StringTokenizer tok;

		public Scanner(InputStream is) {
			br = new BufferedReader(new InputStreamReader(is));
		}

		private void getLine() {
			try {
				while (!hasNext()) {
					tok = new StringTokenizer(br.readLine());
				}
			} catch (IOException e) { /* ignore */
			}
		}

		private boolean hasNext() {
			return tok != null && tok.hasMoreTokens();
		}

		public String next() {
			getLine();
			return tok.nextToken();
		}

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

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

		public void close() {
			try {
				br.close();
			} catch (IOException e) { /* ignore */
			}
		}
	}
}

import java.util.*;
import java.io.*;
public class lp1{
static PrintWriter out = new PrintWriter(System.out);

static void fun(int a[],int is,int in,long sum,ArrayList<Long> arr,int m)
{
        if(is==in)
           {
              arr.add(sum);
              return;
           }
         fun(a,is+1,in,(sum+a[is])%m,arr,m);
         fun(a,is+1,in,sum,arr,m);
}
public static void main(String[] args){

int n = ni();
int m = ni();
int a[] = ai(n);

ArrayList<Long> a1 = new ArrayList();
ArrayList<Long> a2 = new ArrayList();

  fun(a,0,n/2,0,a1,m);
  fun(a,n/2,n,0,a2,m);

Collections.sort(a2);

long ans=0;

for(int i=0;i<a1.size();i++)
{
    long x = a1.get(i);
    int l=0,r=a2.size();

    while((r-l)>1)
     {
           int mid = (l+r)/2;
           if((x+a2.get(mid))<m)
               { ans = Math.max(ans,x+a2.get(mid));l=mid;}
           else
               r=mid;
     }
}
   pn(ans);

   out.flush();
}
static int[] ai(int n)  // it will give in array of size n
{
    int a[] = new int[n];
    for(int i=0;i<n;i++)
        a[i] = ni();
    return a;
}
static long[] al(int n)  // it will give in array of size n
{
    long a[] = new long[n];
    for(int i=0;i<n;i++)
        a[i] = nl();
    return a;
}

static void p(Object o)
{
   out.print(o);
}
static void pn(Object o)
{
    out.println(o);
}
static int abs(int x)
{
    return x>0 ? x : -x;
}
static long gcd(long a,long b)
{
       if(b%a==0)
          return a;
          return gcd(b%a,a);
}
static void subtract_1(char s[]) // it will subtract 1 from the given number.  number should be positive
{
      if(s[0]=='0') // number is zero
          return;
     int n = s.length,i=n-1;
     while(s[i]=='0')
       i--;
     s[i] = (char)((int)(s[i]-'0') + 47);

     for(int j=i+1;j<n;j++)
         s[j]='9';
}
static long pow(long a,long b,long md)
{
    long ans=1;
    while(b>0)
    {
         if(b%2==1)
           ans = (ans*a)%md;
           a = (a*a)%md;
           b = b/2;
    }
   return ans;
}
static long min(long a,long b){

     return a<b ? a : b;
}
static long max(long a,long b){
     return a>b ? a : b;
}
static boolean pal(String s)
{
   int n = s.length(),i1=0,i2=n-1;

     while(i1<i2)
     {
        if(s.charAt(i1)!=s.charAt(i2))
             return false;
             i1++; i2--;
     }
       return true;
}
static String rev(String r)
{
    String s = "";
    int i= r.length()-1;

    while(i>=0)
    {
        s=s+r.charAt(i);
        i--;
    }
       return s;
}
static FastReader sc=new FastReader();

      static int ni(){
                 int x = sc.nextInt();
                 return(x);
        }
      static long nl(){
              long x = sc.nextLong();
              return(x);
         }
      static String n(){
                 String str = sc.next();
                     return(str);
       }
     static String ns(){
                 String str = sc.nextLine();
                   return(str);
      }
     static double nd(){
               double d = sc.nextDouble();
                 return(d);
       }
  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;
        }
    }
}

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

    public  class Sample implements Runnable
    {

          public static void solve()
          {

            int n=i();
            int m=i();
            int[] a=new int[n+1];
            for(int i=0;i<n;i++)
            {
              a[i]=i();
              a[i]=a[i]%m;
            }
            for(int i=0;i<n;i++)out.print(a[i]+" ");
              out.println("");
            int[] dp=new int[n+1];
            dp[0]=a[0];
            long max=0;

            long num=(long)Math.pow(2,n);
            long i=num;
            for(i=1;i<=num;i++)
            {
              long j=i;
              int count=0;
              long ans=0;
              while(j!=0)
              {
                  if(j%2==1)
                  {
                    ans+=a[count];
                  }
                  count++;

                  j>>=1;
              }
            //  out.println("lol");

              max=Math.max(max,ans%m);
            }

            out.println(max);
          }

          public void run()
          {
              solve();
              out.close();
          }

          public static void main(String[] args) throws IOException
          {
                new Thread(null, new Sample(), "whatever", 1<<26).start();
          }
         static class Pair implements Comparable<Pair>
         {
            long a;
            int b;
            Pair(){}
            Pair(long a,int b)
            {
                       this.a=a;
                       this.b=b;
            }

            public int compareTo(Pair x)
           {
                return Long.compare(x.a,this.a);
           }
        }

    ////////////////////////////////////////////////////// Merge Sort ////////////////////////////////////////////////////////////////////////

   static class Merge
   {

        public static void sort(long inputArr[])
        {
            int length = inputArr.length;
            doMergeSort(inputArr,0, length - 1);
        }

        private static void doMergeSort(long[] arr,int lowerIndex, int higherIndex)
        {
            if (lowerIndex < higherIndex) {
                int middle = lowerIndex + (higherIndex - lowerIndex) / 2;
                doMergeSort(arr,lowerIndex, middle);
                doMergeSort(arr,middle + 1, higherIndex);
                mergeParts(arr,lowerIndex, middle, higherIndex);
            }
        }

        private static void mergeParts(long[]array,int lowerIndex, int middle, int higherIndex)
        {
            long[] temp=new long[higherIndex-lowerIndex+1];
            for (int i = lowerIndex; i <= higherIndex; i++)
            {
                temp[i-lowerIndex] = array[i];
            }
            int i = lowerIndex;
            int j = middle + 1;
            int k = lowerIndex;
            while (i <= middle && j <= higherIndex)
            {
                if (temp[i-lowerIndex] < temp[j-lowerIndex])
                {
                    array[k] = temp[i-lowerIndex];
                    i++;
                } else {
                    array[k] = temp[j-lowerIndex];
                    j++;
                }
                k++;
            }
            while (i <= middle)
            {
                array[k] = temp[i-lowerIndex];
                k++;
                i++;
            }
            while(j<=higherIndex)
            {
                array[k]=temp[j-lowerIndex];
                k++;
                j++;
            }
        }

    }

    /////////////////////////////////////////////////////////// Methods ////////////////////////////////////////////////////////////////////////

     static boolean isPal(String s)
     {
        for(int i=0, j=s.length()-1;i<=j;i++,j--)
        {
                if(s.charAt(i)!=s.charAt(j)) return false;
        }
        return true;
     }
     static String rev(String s)
     {
                StringBuilder sb=new StringBuilder(s);
                sb.reverse();
                return sb.toString();
     }
     static int gcd(int a,int b){return (a==0)?b:gcd(b%a,a);}
     static long gcdExtended(long a,long b,long[] x)
     {

        if(a==0){
            x[0]=0;
            x[1]=1;
            return b;
        }
        long[] y=new long[2];
        long gcd=gcdExtended(b%a, a, y);

        x[0]=y[1]-(b/a)*y[0];
        x[1]=y[0];

        return gcd;
    }

     boolean findSum(int set[], int n, long sum)
    {
      if (sum == 0)
         return true;
      if (n == 0 && sum != 0)
         return false;
      if (set[n-1] > sum)
         return findSum(set, n-1, sum);
      return findSum(set, n-1, sum) ||findSum(set, n-1, sum-set[n-1]);
    }

      public static long modPow(long base, long exp, long mod)
     {
        base = base % mod;
        long result = 1;
        while (exp > 0)
       {
            if (exp % 2 == 1)
            {
                result = (result * base) % mod;
            }
            base = (base * base) % mod;
            exp = exp >> 1;
       }
        return result;
    }

    static long[] fac;
    static long[] inv;
    static long mod=(long)1e9+7;
    public static void cal()
    {
        fac = new long[1000005];
        inv = new long[1000005];
        fac[0] = 1;
        inv[0] = 1;
        for (int i = 1; i <= 1000000; i++)
        {
            fac[i] = (fac[i - 1] * i) % mod;
            inv[i] = (inv[i - 1] * modPow(i, mod - 2, mod)) % mod;
        }
    }

    public static long ncr(int n, int r)
    {
        return (((fac[n] * inv[r]) % mod) * inv[n - r]) % mod;
    }

////////////////////////////////////////// Input Reader ////////////////////////////////////////////////////////////////////////////////////////////////////

    static InputReader sc = new InputReader(System.in);
    static PrintWriter out= new PrintWriter(System.out);

    static class InputReader {

          private final InputStream stream;
          private final byte[] buf = new byte[8192];
          private int curChar, snumChars;
          private SpaceCharFilter filter;

          public InputReader(InputStream stream) {
                  this.stream = stream;
          }

          public int snext()
         {
                  if (snumChars == -1)
                          throw new InputMismatchException();
                  if (curChar >= snumChars) {
                          curChar = 0;
                          try {
                                  snumChars = stream.read(buf);
                          } catch (IOException e) {
                                  throw new InputMismatchException();
                          }
                          if (snumChars <= 0)
                                  return -1;
                  }
                  return buf[curChar++];
          }

          public int nextInt()
         {
                  int c = snext();
                  while (isSpaceChar(c))
                  {
                          c = snext();
                  }
                  int sgn = 1;
                  if (c == '-')
                  {
                          sgn = -1;
                          c = snext();
                  }
                  int res = 0;
                  do {
                          if (c < '0' || c > '9')
                                  throw new InputMismatchException();
                          res *= 10;
                          res += c - '0';
                          c = snext();
                  } while (!isSpaceChar(c));
                  return res * sgn;
          }

          public long nextLong()
          {
                  int c = snext();
                  while (isSpaceChar(c))
                  {
                          c = snext();
                  }
                  int sgn = 1;
                  if (c == '-')
                  {
                          sgn = -1;
                          c = snext();
                  }
                  long res = 0;
                  do {
                          if (c < '0' || c > '9')
                                  throw new InputMismatchException();
                          res *= 10;
                          res += c - '0';
                          c = snext();
                  } while (!isSpaceChar(c));
                  return res * sgn;
          }

          public int[] nextIntArray(int n)
          {
                  int a[] = new int[n];
                  for (int i = 0; i < n; i++)
                  {
                          a[i] = nextInt();
                  }
                  return a;
          }

          public long[] nextLongArray(int n)
          {
                  long a[] = new long[n];
                  for (int i = 0; i < n; i++)
                  {
                          a[i] = nextLong();
                  }
                  return a;
          }

          public String nextLine()
         {
                  int c = snext();
                  while (isSpaceChar(c))
                          c = snext();
                  StringBuilder res = new StringBuilder();
                  do {
                          res.appendCodePoint(c);
                          c = snext();
                  } while (!isEndOfLine(c));
                  return res.toString();
          }

          public boolean isSpaceChar(int c)
          {
                  if (filter != null)
                          return filter.isSpaceChar(c);
                  return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
          }

          private boolean isEndOfLine(int c)
          {
                  return c == '\n' || c == '\r' || c == -1;
          }

          public interface SpaceCharFilter
          {
                  public boolean isSpaceChar(int ch);
          }

    }

    static int i()
    {
        return sc.nextInt();
    }
    static long l(){
        return sc.nextLong();
    }
    static int[] iarr(int n)
    {
        return sc.nextIntArray(n);
    }
    static long[] larr(int n)
    {
        return sc.nextLongArray(n);
    }
    static String s(){
        return sc.nextLine();
    }

 }

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

    public  class Sample implements Runnable
    {

          public static void solve()
          {

            int n=i();
            int m=i();
            int[] a=new int[n];
            for(int i=0;i<n;i++)
            {
              a[i]=i();
              a[i]=a[i]%m;
            }
            int[] dp=new int[n+1];
            dp[0]=a[0];
            for(int i=1;i<n;i++)
            {
               dp[i]=Math.max(a[i],(dp[i-1]+a[i])%m);
            }
            int max=0;
            for(int i=0;i<n;i++)max=Math.max(max,dp[i]);
            out.println(max);
          }

          public void run()
          {
              solve();
              out.close();
          }

          public static void main(String[] args) throws IOException
          {
                new Thread(null, new Sample(), "whatever", 1<<26).start();
          }
         static class Pair implements Comparable<Pair>
         {
            long a;
            int b;
            Pair(){}
            Pair(long a,int b)
            {
                       this.a=a;
                       this.b=b;
            }

            public int compareTo(Pair x)
           {
                return Long.compare(x.a,this.a);
           }
        }

    ////////////////////////////////////////////////////// Merge Sort ////////////////////////////////////////////////////////////////////////

   static class Merge
   {

        public static void sort(long inputArr[])
        {
            int length = inputArr.length;
            doMergeSort(inputArr,0, length - 1);
        }

        private static void doMergeSort(long[] arr,int lowerIndex, int higherIndex)
        {
            if (lowerIndex < higherIndex) {
                int middle = lowerIndex + (higherIndex - lowerIndex) / 2;
                doMergeSort(arr,lowerIndex, middle);
                doMergeSort(arr,middle + 1, higherIndex);
                mergeParts(arr,lowerIndex, middle, higherIndex);
            }
        }

        private static void mergeParts(long[]array,int lowerIndex, int middle, int higherIndex)
        {
            long[] temp=new long[higherIndex-lowerIndex+1];
            for (int i = lowerIndex; i <= higherIndex; i++)
            {
                temp[i-lowerIndex] = array[i];
            }
            int i = lowerIndex;
            int j = middle + 1;
            int k = lowerIndex;
            while (i <= middle && j <= higherIndex)
            {
                if (temp[i-lowerIndex] < temp[j-lowerIndex])
                {
                    array[k] = temp[i-lowerIndex];
                    i++;
                } else {
                    array[k] = temp[j-lowerIndex];
                    j++;
                }
                k++;
            }
            while (i <= middle)
            {
                array[k] = temp[i-lowerIndex];
                k++;
                i++;
            }
            while(j<=higherIndex)
            {
                array[k]=temp[j-lowerIndex];
                k++;
                j++;
            }
        }

    }

    /////////////////////////////////////////////////////////// Methods ////////////////////////////////////////////////////////////////////////

     static boolean isPal(String s)
     {
        for(int i=0, j=s.length()-1;i<=j;i++,j--)
        {
                if(s.charAt(i)!=s.charAt(j)) return false;
        }
        return true;
     }
     static String rev(String s)
     {
                StringBuilder sb=new StringBuilder(s);
                sb.reverse();
                return sb.toString();
     }
     static int gcd(int a,int b){return (a==0)?b:gcd(b%a,a);}
     static long gcdExtended(long a,long b,long[] x)
     {

        if(a==0){
            x[0]=0;
            x[1]=1;
            return b;
        }
        long[] y=new long[2];
        long gcd=gcdExtended(b%a, a, y);

        x[0]=y[1]-(b/a)*y[0];
        x[1]=y[0];

        return gcd;
    }

     boolean findSum(int set[], int n, long sum)
    {
      if (sum == 0)
         return true;
      if (n == 0 && sum != 0)
         return false;
      if (set[n-1] > sum)
         return findSum(set, n-1, sum);
      return findSum(set, n-1, sum) ||findSum(set, n-1, sum-set[n-1]);
    }

      public static long modPow(long base, long exp, long mod)
     {
        base = base % mod;
        long result = 1;
        while (exp > 0)
       {
            if (exp % 2 == 1)
            {
                result = (result * base) % mod;
            }
            base = (base * base) % mod;
            exp = exp >> 1;
       }
        return result;
    }

    static long[] fac;
    static long[] inv;
    static long mod=(long)1e9+7;
    public static void cal()
    {
        fac = new long[1000005];
        inv = new long[1000005];
        fac[0] = 1;
        inv[0] = 1;
        for (int i = 1; i <= 1000000; i++)
        {
            fac[i] = (fac[i - 1] * i) % mod;
            inv[i] = (inv[i - 1] * modPow(i, mod - 2, mod)) % mod;
        }
    }

    public static long ncr(int n, int r)
    {
        return (((fac[n] * inv[r]) % mod) * inv[n - r]) % mod;
    }

////////////////////////////////////////// Input Reader ////////////////////////////////////////////////////////////////////////////////////////////////////

    static InputReader sc = new InputReader(System.in);
    static PrintWriter out= new PrintWriter(System.out);

    static class InputReader {

          private final InputStream stream;
          private final byte[] buf = new byte[8192];
          private int curChar, snumChars;
          private SpaceCharFilter filter;

          public InputReader(InputStream stream) {
                  this.stream = stream;
          }

          public int snext()
         {
                  if (snumChars == -1)
                          throw new InputMismatchException();
                  if (curChar >= snumChars) {
                          curChar = 0;
                          try {
                                  snumChars = stream.read(buf);
                          } catch (IOException e) {
                                  throw new InputMismatchException();
                          }
                          if (snumChars <= 0)
                                  return -1;
                  }
                  return buf[curChar++];
          }

          public int nextInt()
         {
                  int c = snext();
                  while (isSpaceChar(c))
                  {
                          c = snext();
                  }
                  int sgn = 1;
                  if (c == '-')
                  {
                          sgn = -1;
                          c = snext();
                  }
                  int res = 0;
                  do {
                          if (c < '0' || c > '9')
                                  throw new InputMismatchException();
                          res *= 10;
                          res += c - '0';
                          c = snext();
                  } while (!isSpaceChar(c));
                  return res * sgn;
          }

          public long nextLong()
          {
                  int c = snext();
                  while (isSpaceChar(c))
                  {
                          c = snext();
                  }
                  int sgn = 1;
                  if (c == '-')
                  {
                          sgn = -1;
                          c = snext();
                  }
                  long res = 0;
                  do {
                          if (c < '0' || c > '9')
                                  throw new InputMismatchException();
                          res *= 10;
                          res += c - '0';
                          c = snext();
                  } while (!isSpaceChar(c));
                  return res * sgn;
          }

          public int[] nextIntArray(int n)
          {
                  int a[] = new int[n];
                  for (int i = 0; i < n; i++)
                  {
                          a[i] = nextInt();
                  }
                  return a;
          }

          public long[] nextLongArray(int n)
          {
                  long a[] = new long[n];
                  for (int i = 0; i < n; i++)
                  {
                          a[i] = nextLong();
                  }
                  return a;
          }

          public String nextLine()
         {
                  int c = snext();
                  while (isSpaceChar(c))
                          c = snext();
                  StringBuilder res = new StringBuilder();
                  do {
                          res.appendCodePoint(c);
                          c = snext();
                  } while (!isEndOfLine(c));
                  return res.toString();
          }

          public boolean isSpaceChar(int c)
          {
                  if (filter != null)
                          return filter.isSpaceChar(c);
                  return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
          }

          private boolean isEndOfLine(int c)
          {
                  return c == '\n' || c == '\r' || c == -1;
          }

          public interface SpaceCharFilter
          {
                  public boolean isSpaceChar(int ch);
          }

    }

    static int i()
    {
        return sc.nextInt();
    }
    static long l(){
        return sc.nextLong();
    }
    static int[] iarr(int n)
    {
        return sc.nextIntArray(n);
    }
    static long[] larr(int n)
    {
        return sc.nextLongArray(n);
    }
    static String s(){
        return sc.nextLine();
    }

 }

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

    public  class Sample implements Runnable
    {
          static int[] X;

          static int[] Y;//=new int[2000005];
          public static int[] a=new int[2000005];
          static int n,m;

          public static void solve()
          {

            n=i();
            m=i();
            X=new int[(1<<n/2)];
            Y=new int[(1<<(n-n/2))];

            for(int i=0;i<n;i++)
            {
              a[i]=i();
              a[i]=a[i]%m;
            }

              Arrays.fill(Y,Integer.MAX_VALUE);

            call(X,n/2,0);
            call(Y,n-n/2,n/2);
            Arrays.sort(Y);

            int max=Y[(1<<(n-n/2))-1];

            for(int i=0;i<(1<<(n/2));i++)
            {
                int index=upperbound(Y,0,(1<<(n-n/2)),m-1-X[i],i)-1;

                if(index!=-1)
                 {  max=Math.max(max,(X[i]+Y[index])%m);}

                max=Math.max(max,X[i]);

            }
            out.println(max);

          }
          public static int upperbound(int[] A,int low,int high,int val,int ind)
          {
            int ans=0;

            while(low<high)
            {

              int mid=(low+high)>>1;
              if(A[mid]<=val)low=mid+1;
              else
              {
                ans=mid;
                high=mid;
              }
            }
            return low;
          }
          public static void call(int[] AA,int N,int c)
          {

            for(int i=0;i<(1<<N);i++)
            {  int ans=0;
               for(int j=0;j<N;j++)
               {
                if((i&(1<<j))>=1)
                { //out.println(i+" "+(j+c)+" " );
                  ans+=a[j+c];
                }
               }

               AA[i]=ans%m;

            }

          }

          public void run()
          {
              solve();
              out.close();
          }

          public static void main(String[] args) throws IOException
          {
                new Thread(null, new Sample(), "whatever", 1<<26).start();
          }
         static class Pair implements Comparable<Pair>
         {
            long a;
            int b;
            Pair(){}
            Pair(long a,int b)
            {
                       this.a=a;
                       this.b=b;
            }

            public int compareTo(Pair x)
           {
                return Long.compare(x.a,this.a);
           }
        }

    ////////////////////////////////////////////////////// Merge Sort ////////////////////////////////////////////////////////////////////////

   static class Merge
   {

        public static void sort(long inputArr[])
        {
            int length = inputArr.length;
            doMergeSort(inputArr,0, length - 1);
        }

        private static void doMergeSort(long[] arr,int lowerIndex, int higherIndex)
        {
            if (lowerIndex < higherIndex) {
                int middle = lowerIndex + (higherIndex - lowerIndex) / 2;
                doMergeSort(arr,lowerIndex, middle);
                doMergeSort(arr,middle + 1, higherIndex);
                mergeParts(arr,lowerIndex, middle, higherIndex);
            }
        }

        private static void mergeParts(long[]array,int lowerIndex, int middle, int higherIndex)
        {
            long[] temp=new long[higherIndex-lowerIndex+1];
            for (int i = lowerIndex; i <= higherIndex; i++)
            {
                temp[i-lowerIndex] = array[i];
            }
            int i = lowerIndex;
            int j = middle + 1;
            int k = lowerIndex;
            while (i <= middle && j <= higherIndex)
            {
                if (temp[i-lowerIndex] < temp[j-lowerIndex])
                {
                    array[k] = temp[i-lowerIndex];
                    i++;
                } else {
                    array[k] = temp[j-lowerIndex];
                    j++;
                }
                k++;
            }
            while (i <= middle)
            {
                array[k] = temp[i-lowerIndex];
                k++;
                i++;
            }
            while(j<=higherIndex)
            {
                array[k]=temp[j-lowerIndex];
                k++;
                j++;
            }
        }

    }

    /////////////////////////////////////////////////////////// Methods ////////////////////////////////////////////////////////////////////////

     static boolean isPal(String s)
     {
        for(int i=0, j=s.length()-1;i<=j;i++,j--)
        {
                if(s.charAt(i)!=s.charAt(j)) return false;
        }
        return true;
     }
     static String rev(String s)
     {
                StringBuilder sb=new StringBuilder(s);
                sb.reverse();
                return sb.toString();
     }
     static int gcd(int a,int b){return (a==0)?b:gcd(b%a,a);}
     static long gcdExtended(long a,long b,long[] x)
     {

        if(a==0){
            x[0]=0;
            x[1]=1;
            return b;
        }
        long[] y=new long[2];
        long gcd=gcdExtended(b%a, a, y);

        x[0]=y[1]-(b/a)*y[0];
        x[1]=y[0];

        return gcd;
    }

     boolean findSum(int set[], int n, long sum)
    {
      if (sum == 0)
         return true;
      if (n == 0 && sum != 0)
         return false;
      if (set[n-1] > sum)
         return findSum(set, n-1, sum);
      return findSum(set, n-1, sum) ||findSum(set, n-1, sum-set[n-1]);
    }

      public static long modPow(long base, long exp, long mod)
     {
        base = base % mod;
        long result = 1;
        while (exp > 0)
       {
            if (exp % 2 == 1)
            {
                result = (result * base) % mod;
            }
            base = (base * base) % mod;
            exp = exp >> 1;
       }
        return result;
    }

    static long[] fac;
    static long[] inv;
    static long mod=(long)1e9+7;
    public static void cal()
    {
        fac = new long[1000005];
        inv = new long[1000005];
        fac[0] = 1;
        inv[0] = 1;
        for (int i = 1; i <= 1000000; i++)
        {
            fac[i] = (fac[i - 1] * i) % mod;
            inv[i] = (inv[i - 1] * modPow(i, mod - 2, mod)) % mod;
        }
    }

    public static long ncr(int n, int r)
    {
        return (((fac[n] * inv[r]) % mod) * inv[n - r]) % mod;
    }

////////////////////////////////////////// Input Reader ////////////////////////////////////////////////////////////////////////////////////////////////////

    static InputReader sc = new InputReader(System.in);
    static PrintWriter out= new PrintWriter(System.out);

    static class InputReader {

          private final InputStream stream;
          private final byte[] buf = new byte[8192];
          private int curChar, snumChars;
          private SpaceCharFilter filter;

          public InputReader(InputStream stream) {
                  this.stream = stream;
          }

          public int snext()
         {
                  if (snumChars == -1)
                          throw new InputMismatchException();
                  if (curChar >= snumChars) {
                          curChar = 0;
                          try {
                                  snumChars = stream.read(buf);
                          } catch (IOException e) {
                                  throw new InputMismatchException();
                          }
                          if (snumChars <= 0)
                                  return -1;
                  }
                  return buf[curChar++];
          }

          public int nextInt()
         {
                  int c = snext();
                  while (isSpaceChar(c))
                  {
                          c = snext();
                  }
                  int sgn = 1;
                  if (c == '-')
                  {
                          sgn = -1;
                          c = snext();
                  }
                  int res = 0;
                  do {
                          if (c < '0' || c > '9')
                                  throw new InputMismatchException();
                          res *= 10;
                          res += c - '0';
                          c = snext();
                  } while (!isSpaceChar(c));
                  return res * sgn;
          }

          public long nextLong()
          {
                  int c = snext();
                  while (isSpaceChar(c))
                  {
                          c = snext();
                  }
                  int sgn = 1;
                  if (c == '-')
                  {
                          sgn = -1;
                          c = snext();
                  }
                  long res = 0;
                  do {
                          if (c < '0' || c > '9')
                                  throw new InputMismatchException();
                          res *= 10;
                          res += c - '0';
                          c = snext();
                  } while (!isSpaceChar(c));
                  return res * sgn;
          }

          public int[] nextIntArray(int n)
          {
                  int a[] = new int[n];
                  for (int i = 0; i < n; i++)
                  {
                          a[i] = nextInt();
                  }
                  return a;
          }

          public long[] nextLongArray(int n)
          {
                  long a[] = new long[n];
                  for (int i = 0; i < n; i++)
                  {
                          a[i] = nextLong();
                  }
                  return a;
          }

          public String nextLine()
         {
                  int c = snext();
                  while (isSpaceChar(c))
                          c = snext();
                  StringBuilder res = new StringBuilder();
                  do {
                          res.appendCodePoint(c);
                          c = snext();
                  } while (!isEndOfLine(c));
                  return res.toString();
          }

          public boolean isSpaceChar(int c)
          {
                  if (filter != null)
                          return filter.isSpaceChar(c);
                  return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
          }

          private boolean isEndOfLine(int c)
          {
                  return c == '\n' || c == '\r' || c == -1;
          }

          public interface SpaceCharFilter
          {
                  public boolean isSpaceChar(int ch);
          }

    }

    static int i()
    {
        return sc.nextInt();
    }
    static long l(){
        return sc.nextLong();
    }
    static int[] iarr(int n)
    {
        return sc.nextIntArray(n);
    }
    static long[] larr(int n)
    {
        return sc.nextLongArray(n);
    }
    static String s(){
        return sc.nextLine();
    }

 }

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

    public  class Sample implements Runnable
    {

          public static void solve()
          {

            int n=i();
            int m=i();
            int[] a=new int[n];
            for(int i=0;i<n;i++)
            {
              a[i]=i();
              a[i]=a[i]%m;
            }

            int[] dp=new int[n+1];
            dp[0]=a[0];
            int max=0;

            long num=(long)Math.pow(2,n);
            long i=num;
            for(i=0;i<=num;i++)
            {
              long j=i;
              int count=0;
              int ans=0;
              while(j!=0)
              {
                  if(j%2==0)
                  {
                    ans+=a[count];
                  }
                  count++;
                  j>>=1;
              }
              max=Math.max(max,ans%m);
            }

            out.println(max);
          }

          public void run()
          {
              solve();
              out.close();
          }

          public static void main(String[] args) throws IOException
          {
                new Thread(null, new Sample(), "whatever", 1<<26).start();
          }
         static class Pair implements Comparable<Pair>
         {
            long a;
            int b;
            Pair(){}
            Pair(long a,int b)
            {
                       this.a=a;
                       this.b=b;
            }

            public int compareTo(Pair x)
           {
                return Long.compare(x.a,this.a);
           }
        }

    ////////////////////////////////////////////////////// Merge Sort ////////////////////////////////////////////////////////////////////////

   static class Merge
   {

        public static void sort(long inputArr[])
        {
            int length = inputArr.length;
            doMergeSort(inputArr,0, length - 1);
        }

        private static void doMergeSort(long[] arr,int lowerIndex, int higherIndex)
        {
            if (lowerIndex < higherIndex) {
                int middle = lowerIndex + (higherIndex - lowerIndex) / 2;
                doMergeSort(arr,lowerIndex, middle);
                doMergeSort(arr,middle + 1, higherIndex);
                mergeParts(arr,lowerIndex, middle, higherIndex);
            }
        }

        private static void mergeParts(long[]array,int lowerIndex, int middle, int higherIndex)
        {
            long[] temp=new long[higherIndex-lowerIndex+1];
            for (int i = lowerIndex; i <= higherIndex; i++)
            {
                temp[i-lowerIndex] = array[i];
            }
            int i = lowerIndex;
            int j = middle + 1;
            int k = lowerIndex;
            while (i <= middle && j <= higherIndex)
            {
                if (temp[i-lowerIndex] < temp[j-lowerIndex])
                {
                    array[k] = temp[i-lowerIndex];
                    i++;
                } else {
                    array[k] = temp[j-lowerIndex];
                    j++;
                }
                k++;
            }
            while (i <= middle)
            {
                array[k] = temp[i-lowerIndex];
                k++;
                i++;
            }
            while(j<=higherIndex)
            {
                array[k]=temp[j-lowerIndex];
                k++;
                j++;
            }
        }

    }

    /////////////////////////////////////////////////////////// Methods ////////////////////////////////////////////////////////////////////////

     static boolean isPal(String s)
     {
        for(int i=0, j=s.length()-1;i<=j;i++,j--)
        {
                if(s.charAt(i)!=s.charAt(j)) return false;
        }
        return true;
     }
     static String rev(String s)
     {
                StringBuilder sb=new StringBuilder(s);
                sb.reverse();
                return sb.toString();
     }
     static int gcd(int a,int b){return (a==0)?b:gcd(b%a,a);}
     static long gcdExtended(long a,long b,long[] x)
     {

        if(a==0){
            x[0]=0;
            x[1]=1;
            return b;
        }
        long[] y=new long[2];
        long gcd=gcdExtended(b%a, a, y);

        x[0]=y[1]-(b/a)*y[0];
        x[1]=y[0];

        return gcd;
    }

     boolean findSum(int set[], int n, long sum)
    {
      if (sum == 0)
         return true;
      if (n == 0 && sum != 0)
         return false;
      if (set[n-1] > sum)
         return findSum(set, n-1, sum);
      return findSum(set, n-1, sum) ||findSum(set, n-1, sum-set[n-1]);
    }

      public static long modPow(long base, long exp, long mod)
     {
        base = base % mod;
        long result = 1;
        while (exp > 0)
       {
            if (exp % 2 == 1)
            {
                result = (result * base) % mod;
            }
            base = (base * base) % mod;
            exp = exp >> 1;
       }
        return result;
    }

    static long[] fac;
    static long[] inv;
    static long mod=(long)1e9+7;
    public static void cal()
    {
        fac = new long[1000005];
        inv = new long[1000005];
        fac[0] = 1;
        inv[0] = 1;
        for (int i = 1; i <= 1000000; i++)
        {
            fac[i] = (fac[i - 1] * i) % mod;
            inv[i] = (inv[i - 1] * modPow(i, mod - 2, mod)) % mod;
        }
    }

    public static long ncr(int n, int r)
    {
        return (((fac[n] * inv[r]) % mod) * inv[n - r]) % mod;
    }

////////////////////////////////////////// Input Reader ////////////////////////////////////////////////////////////////////////////////////////////////////

    static InputReader sc = new InputReader(System.in);
    static PrintWriter out= new PrintWriter(System.out);

    static class InputReader {

          private final InputStream stream;
          private final byte[] buf = new byte[8192];
          private int curChar, snumChars;
          private SpaceCharFilter filter;

          public InputReader(InputStream stream) {
                  this.stream = stream;
          }

          public int snext()
         {
                  if (snumChars == -1)
                          throw new InputMismatchException();
                  if (curChar >= snumChars) {
                          curChar = 0;
                          try {
                                  snumChars = stream.read(buf);
                          } catch (IOException e) {
                                  throw new InputMismatchException();
                          }
                          if (snumChars <= 0)
                                  return -1;
                  }
                  return buf[curChar++];
          }

          public int nextInt()
         {
                  int c = snext();
                  while (isSpaceChar(c))
                  {
                          c = snext();
                  }
                  int sgn = 1;
                  if (c == '-')
                  {
                          sgn = -1;
                          c = snext();
                  }
                  int res = 0;
                  do {
                          if (c < '0' || c > '9')
                                  throw new InputMismatchException();
                          res *= 10;
                          res += c - '0';
                          c = snext();
                  } while (!isSpaceChar(c));
                  return res * sgn;
          }

          public long nextLong()
          {
                  int c = snext();
                  while (isSpaceChar(c))
                  {
                          c = snext();
                  }
                  int sgn = 1;
                  if (c == '-')
                  {
                          sgn = -1;
                          c = snext();
                  }
                  long res = 0;
                  do {
                          if (c < '0' || c > '9')
                                  throw new InputMismatchException();
                          res *= 10;
                          res += c - '0';
                          c = snext();
                  } while (!isSpaceChar(c));
                  return res * sgn;
          }

          public int[] nextIntArray(int n)
          {
                  int a[] = new int[n];
                  for (int i = 0; i < n; i++)
                  {
                          a[i] = nextInt();
                  }
                  return a;
          }

          public long[] nextLongArray(int n)
          {
                  long a[] = new long[n];
                  for (int i = 0; i < n; i++)
                  {
                          a[i] = nextLong();
                  }
                  return a;
          }

          public String nextLine()
         {
                  int c = snext();
                  while (isSpaceChar(c))
                          c = snext();
                  StringBuilder res = new StringBuilder();
                  do {
                          res.appendCodePoint(c);
                          c = snext();
                  } while (!isEndOfLine(c));
                  return res.toString();
          }

          public boolean isSpaceChar(int c)
          {
                  if (filter != null)
                          return filter.isSpaceChar(c);
                  return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
          }

          private boolean isEndOfLine(int c)
          {
                  return c == '\n' || c == '\r' || c == -1;
          }

          public interface SpaceCharFilter
          {
                  public boolean isSpaceChar(int ch);
          }

    }

    static int i()
    {
        return sc.nextInt();
    }
    static long l(){
        return sc.nextLong();
    }
    static int[] iarr(int n)
    {
        return sc.nextIntArray(n);
    }
    static long[] larr(int n)
    {
        return sc.nextLongArray(n);
    }
    static String s(){
        return sc.nextLine();
    }

 }

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

    public  class Sample implements Runnable
    {
          static int[] X=new int[2000005];
          static int[] Y=new int[2000005];
          public static int[] a=new int[2000005];
          static int n,m;

          public static void solve()
          {

            n=i();
            m=i();

            for(int i=0;i<n;i++)
            {
              a[i]=i();
              a[i]=a[i]%m;
            }

              Arrays.fill(Y,Integer.MAX_VALUE);

            call(X,n/2,0);
            call(Y,n-n/2,n/2);
            Arrays.sort(Y);
            int max=Y[n-n/2];

            for(int i=0;i<(1<<(n/2));i++)
            {
                int index=upperbound(Y,0,(1<<(n-n/2)),m-1-X[i])-1;
                if(index!=-1)
                  max=Math.max(max,(X[i]+Y[index])%m);
                max=Math.max(max,X[i]);

            }
            out.println(max);

          }
          public static int upperbound(int[] A,int low,int high,int val)
          {
            int ans=0;
            if(val<Y[0])return 0;
            if(val>Y[n-n/2]) return(n-n/2);
            while(low<high)
            {
              int mid=(low+high)>>1;
              if(a[mid]<=val)low=mid+1;
              else
              {
                ans=mid;
                high=mid-1;
              }
            }
            return ans;
          }
          public static void call(int[] AA,int N,int c)
          {

            for(int i=0;i<(1<<N);i++)
            {  int ans=0;
               for(int j=0;j<N;j++)
               {
                if((i&(1<<j))>=1)
                { //out.println(i+" "+(j+c)+" " );
                  ans+=a[j+c];
                }
               }

               AA[i]=ans%m;
            }

          }

          public void run()
          {
              solve();
              out.close();
          }

          public static void main(String[] args) throws IOException
          {
                new Thread(null, new Sample(), "whatever", 1<<26).start();
          }
         static class Pair implements Comparable<Pair>
         {
            long a;
            int b;
            Pair(){}
            Pair(long a,int b)
            {
                       this.a=a;
                       this.b=b;
            }

            public int compareTo(Pair x)
           {
                return Long.compare(x.a,this.a);
           }
        }

    ////////////////////////////////////////////////////// Merge Sort ////////////////////////////////////////////////////////////////////////

   static class Merge
   {

        public static void sort(long inputArr[])
        {
            int length = inputArr.length;
            doMergeSort(inputArr,0, length - 1);
        }

        private static void doMergeSort(long[] arr,int lowerIndex, int higherIndex)
        {
            if (lowerIndex < higherIndex) {
                int middle = lowerIndex + (higherIndex - lowerIndex) / 2;
                doMergeSort(arr,lowerIndex, middle);
                doMergeSort(arr,middle + 1, higherIndex);
                mergeParts(arr,lowerIndex, middle, higherIndex);
            }
        }

        private static void mergeParts(long[]array,int lowerIndex, int middle, int higherIndex)
        {
            long[] temp=new long[higherIndex-lowerIndex+1];
            for (int i = lowerIndex; i <= higherIndex; i++)
            {
                temp[i-lowerIndex] = array[i];
            }
            int i = lowerIndex;
            int j = middle + 1;
            int k = lowerIndex;
            while (i <= middle && j <= higherIndex)
            {
                if (temp[i-lowerIndex] < temp[j-lowerIndex])
                {
                    array[k] = temp[i-lowerIndex];
                    i++;
                } else {
                    array[k] = temp[j-lowerIndex];
                    j++;
                }
                k++;
            }
            while (i <= middle)
            {
                array[k] = temp[i-lowerIndex];
                k++;
                i++;
            }
            while(j<=higherIndex)
            {
                array[k]=temp[j-lowerIndex];
                k++;
                j++;
            }
        }

    }

    /////////////////////////////////////////////////////////// Methods ////////////////////////////////////////////////////////////////////////

     static boolean isPal(String s)
     {
        for(int i=0, j=s.length()-1;i<=j;i++,j--)
        {
                if(s.charAt(i)!=s.charAt(j)) return false;
        }
        return true;
     }
     static String rev(String s)
     {
                StringBuilder sb=new StringBuilder(s);
                sb.reverse();
                return sb.toString();
     }
     static int gcd(int a,int b){return (a==0)?b:gcd(b%a,a);}
     static long gcdExtended(long a,long b,long[] x)
     {

        if(a==0){
            x[0]=0;
            x[1]=1;
            return b;
        }
        long[] y=new long[2];
        long gcd=gcdExtended(b%a, a, y);

        x[0]=y[1]-(b/a)*y[0];
        x[1]=y[0];

        return gcd;
    }

     boolean findSum(int set[], int n, long sum)
    {
      if (sum == 0)
         return true;
      if (n == 0 && sum != 0)
         return false;
      if (set[n-1] > sum)
         return findSum(set, n-1, sum);
      return findSum(set, n-1, sum) ||findSum(set, n-1, sum-set[n-1]);
    }

      public static long modPow(long base, long exp, long mod)
     {
        base = base % mod;
        long result = 1;
        while (exp > 0)
       {
            if (exp % 2 == 1)
            {
                result = (result * base) % mod;
            }
            base = (base * base) % mod;
            exp = exp >> 1;
       }
        return result;
    }

    static long[] fac;
    static long[] inv;
    static long mod=(long)1e9+7;
    public static void cal()
    {
        fac = new long[1000005];
        inv = new long[1000005];
        fac[0] = 1;
        inv[0] = 1;
        for (int i = 1; i <= 1000000; i++)
        {
            fac[i] = (fac[i - 1] * i) % mod;
            inv[i] = (inv[i - 1] * modPow(i, mod - 2, mod)) % mod;
        }
    }

    public static long ncr(int n, int r)
    {
        return (((fac[n] * inv[r]) % mod) * inv[n - r]) % mod;
    }

////////////////////////////////////////// Input Reader ////////////////////////////////////////////////////////////////////////////////////////////////////

    static InputReader sc = new InputReader(System.in);
    static PrintWriter out= new PrintWriter(System.out);

    static class InputReader {

          private final InputStream stream;
          private final byte[] buf = new byte[8192];
          private int curChar, snumChars;
          private SpaceCharFilter filter;

          public InputReader(InputStream stream) {
                  this.stream = stream;
          }

          public int snext()
         {
                  if (snumChars == -1)
                          throw new InputMismatchException();
                  if (curChar >= snumChars) {
                          curChar = 0;
                          try {
                                  snumChars = stream.read(buf);
                          } catch (IOException e) {
                                  throw new InputMismatchException();
                          }
                          if (snumChars <= 0)
                                  return -1;
                  }
                  return buf[curChar++];
          }

          public int nextInt()
         {
                  int c = snext();
                  while (isSpaceChar(c))
                  {
                          c = snext();
                  }
                  int sgn = 1;
                  if (c == '-')
                  {
                          sgn = -1;
                          c = snext();
                  }
                  int res = 0;
                  do {
                          if (c < '0' || c > '9')
                                  throw new InputMismatchException();
                          res *= 10;
                          res += c - '0';
                          c = snext();
                  } while (!isSpaceChar(c));
                  return res * sgn;
          }

          public long nextLong()
          {
                  int c = snext();
                  while (isSpaceChar(c))
                  {
                          c = snext();
                  }
                  int sgn = 1;
                  if (c == '-')
                  {
                          sgn = -1;
                          c = snext();
                  }
                  long res = 0;
                  do {
                          if (c < '0' || c > '9')
                                  throw new InputMismatchException();
                          res *= 10;
                          res += c - '0';
                          c = snext();
                  } while (!isSpaceChar(c));
                  return res * sgn;
          }

          public int[] nextIntArray(int n)
          {
                  int a[] = new int[n];
                  for (int i = 0; i < n; i++)
                  {
                          a[i] = nextInt();
                  }
                  return a;
          }

          public long[] nextLongArray(int n)
          {
                  long a[] = new long[n];
                  for (int i = 0; i < n; i++)
                  {
                          a[i] = nextLong();
                  }
                  return a;
          }

          public String nextLine()
         {
                  int c = snext();
                  while (isSpaceChar(c))
                          c = snext();
                  StringBuilder res = new StringBuilder();
                  do {
                          res.appendCodePoint(c);
                          c = snext();
                  } while (!isEndOfLine(c));
                  return res.toString();
          }

          public boolean isSpaceChar(int c)
          {
                  if (filter != null)
                          return filter.isSpaceChar(c);
                  return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
          }

          private boolean isEndOfLine(int c)
          {
                  return c == '\n' || c == '\r' || c == -1;
          }

          public interface SpaceCharFilter
          {
                  public boolean isSpaceChar(int ch);
          }

    }

    static int i()
    {
        return sc.nextInt();
    }
    static long l(){
        return sc.nextLong();
    }
    static int[] iarr(int n)
    {
        return sc.nextIntArray(n);
    }
    static long[] larr(int n)
    {
        return sc.nextLongArray(n);
    }
    static String s(){
        return sc.nextLine();
    }

 }

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

    public  class Sample implements Runnable
    {
          static int[] X=new int[2000005];
          static int[] Y=new int[2000005];
          public static int[] a=new int[2000005];
          static int n,m;

          public static void solve()
          {

            n=i();
            m=i();

            for(int i=0;i<n;i++)
            {
              a[i]=i();
              a[i]=a[i]%m;
            }

              Arrays.fill(Y,Integer.MAX_VALUE);

            call(X,n/2,0);
            call(Y,n-n/2,n/2);
            Arrays.sort(Y);
            int max=Y[(1<<(n-n/2))-1];

            for(int i=0;i<(1<<(n/2));i++)
            {
                int index=upperbound(Y,0,(1<<(n-n/2)),m-1-X[i])-1;
                if(index!=-1)
                  max=Math.max(max,(X[i]+Y[index])%m);
                max=Math.max(max,X[i]);

            }
            out.println(max);

          }
          public static int upperbound(int[] A,int low,int high,int val)
          {
            int ans=0;
            if(val<Y[0])return 0;
            if(val>Y[n-n/2]) return(n-n/2);
            while(low<high)
            {
              int mid=(low+high)>>1;
              if(a[mid]<=val)low=mid+1;
              else
              {
                ans=mid;
                high=mid-1;
              }
            }
            return ans;
          }
          public static void call(int[] AA,int N,int c)
          {

            for(int i=0;i<(1<<N);i++)
            {  int ans=0;
               for(int j=0;j<N;j++)
               {
                if((i&(1<<j))>=1)
                { //out.println(i+" "+(j+c)+" " );
                  ans+=a[j+c];
                }
               }

               AA[i]=ans%m;

            }

          }

          public void run()
          {
              solve();
              out.close();
          }

          public static void main(String[] args) throws IOException
          {
                new Thread(null, new Sample(), "whatever", 1<<26).start();
          }
         static class Pair implements Comparable<Pair>
         {
            long a;
            int b;
            Pair(){}
            Pair(long a,int b)
            {
                       this.a=a;
                       this.b=b;
            }

            public int compareTo(Pair x)
           {
                return Long.compare(x.a,this.a);
           }
        }

    ////////////////////////////////////////////////////// Merge Sort ////////////////////////////////////////////////////////////////////////

   static class Merge
   {

        public static void sort(long inputArr[])
        {
            int length = inputArr.length;
            doMergeSort(inputArr,0, length - 1);
        }

        private static void doMergeSort(long[] arr,int lowerIndex, int higherIndex)
        {
            if (lowerIndex < higherIndex) {
                int middle = lowerIndex + (higherIndex - lowerIndex) / 2;
                doMergeSort(arr,lowerIndex, middle);
                doMergeSort(arr,middle + 1, higherIndex);
                mergeParts(arr,lowerIndex, middle, higherIndex);
            }
        }

        private static void mergeParts(long[]array,int lowerIndex, int middle, int higherIndex)
        {
            long[] temp=new long[higherIndex-lowerIndex+1];
            for (int i = lowerIndex; i <= higherIndex; i++)
            {
                temp[i-lowerIndex] = array[i];
            }
            int i = lowerIndex;
            int j = middle + 1;
            int k = lowerIndex;
            while (i <= middle && j <= higherIndex)
            {
                if (temp[i-lowerIndex] < temp[j-lowerIndex])
                {
                    array[k] = temp[i-lowerIndex];
                    i++;
                } else {
                    array[k] = temp[j-lowerIndex];
                    j++;
                }
                k++;
            }
            while (i <= middle)
            {
                array[k] = temp[i-lowerIndex];
                k++;
                i++;
            }
            while(j<=higherIndex)
            {
                array[k]=temp[j-lowerIndex];
                k++;
                j++;
            }
        }

    }

    /////////////////////////////////////////////////////////// Methods ////////////////////////////////////////////////////////////////////////

     static boolean isPal(String s)
     {
        for(int i=0, j=s.length()-1;i<=j;i++,j--)
        {
                if(s.charAt(i)!=s.charAt(j)) return false;
        }
        return true;
     }
     static String rev(String s)
     {
                StringBuilder sb=new StringBuilder(s);
                sb.reverse();
                return sb.toString();
     }
     static int gcd(int a,int b){return (a==0)?b:gcd(b%a,a);}
     static long gcdExtended(long a,long b,long[] x)
     {

        if(a==0){
            x[0]=0;
            x[1]=1;
            return b;
        }
        long[] y=new long[2];
        long gcd=gcdExtended(b%a, a, y);

        x[0]=y[1]-(b/a)*y[0];
        x[1]=y[0];

        return gcd;
    }

     boolean findSum(int set[], int n, long sum)
    {
      if (sum == 0)
         return true;
      if (n == 0 && sum != 0)
         return false;
      if (set[n-1] > sum)
         return findSum(set, n-1, sum);
      return findSum(set, n-1, sum) ||findSum(set, n-1, sum-set[n-1]);
    }

      public static long modPow(long base, long exp, long mod)
     {
        base = base % mod;
        long result = 1;
        while (exp > 0)
       {
            if (exp % 2 == 1)
            {
                result = (result * base) % mod;
            }
            base = (base * base) % mod;
            exp = exp >> 1;
       }
        return result;
    }

    static long[] fac;
    static long[] inv;
    static long mod=(long)1e9+7;
    public static void cal()
    {
        fac = new long[1000005];
        inv = new long[1000005];
        fac[0] = 1;
        inv[0] = 1;
        for (int i = 1; i <= 1000000; i++)
        {
            fac[i] = (fac[i - 1] * i) % mod;
            inv[i] = (inv[i - 1] * modPow(i, mod - 2, mod)) % mod;
        }
    }

    public static long ncr(int n, int r)
    {
        return (((fac[n] * inv[r]) % mod) * inv[n - r]) % mod;
    }

////////////////////////////////////////// Input Reader ////////////////////////////////////////////////////////////////////////////////////////////////////

    static InputReader sc = new InputReader(System.in);
    static PrintWriter out= new PrintWriter(System.out);

    static class InputReader {

          private final InputStream stream;
          private final byte[] buf = new byte[8192];
          private int curChar, snumChars;
          private SpaceCharFilter filter;

          public InputReader(InputStream stream) {
                  this.stream = stream;
          }

          public int snext()
         {
                  if (snumChars == -1)
                          throw new InputMismatchException();
                  if (curChar >= snumChars) {
                          curChar = 0;
                          try {
                                  snumChars = stream.read(buf);
                          } catch (IOException e) {
                                  throw new InputMismatchException();
                          }
                          if (snumChars <= 0)
                                  return -1;
                  }
                  return buf[curChar++];
          }

          public int nextInt()
         {
                  int c = snext();
                  while (isSpaceChar(c))
                  {
                          c = snext();
                  }
                  int sgn = 1;
                  if (c == '-')
                  {
                          sgn = -1;
                          c = snext();
                  }
                  int res = 0;
                  do {
                          if (c < '0' || c > '9')
                                  throw new InputMismatchException();
                          res *= 10;
                          res += c - '0';
                          c = snext();
                  } while (!isSpaceChar(c));
                  return res * sgn;
          }

          public long nextLong()
          {
                  int c = snext();
                  while (isSpaceChar(c))
                  {
                          c = snext();
                  }
                  int sgn = 1;
                  if (c == '-')
                  {
                          sgn = -1;
                          c = snext();
                  }
                  long res = 0;
                  do {
                          if (c < '0' || c > '9')
                                  throw new InputMismatchException();
                          res *= 10;
                          res += c - '0';
                          c = snext();
                  } while (!isSpaceChar(c));
                  return res * sgn;
          }

          public int[] nextIntArray(int n)
          {
                  int a[] = new int[n];
                  for (int i = 0; i < n; i++)
                  {
                          a[i] = nextInt();
                  }
                  return a;
          }

          public long[] nextLongArray(int n)
          {
                  long a[] = new long[n];
                  for (int i = 0; i < n; i++)
                  {
                          a[i] = nextLong();
                  }
                  return a;
          }

          public String nextLine()
         {
                  int c = snext();
                  while (isSpaceChar(c))
                          c = snext();
                  StringBuilder res = new StringBuilder();
                  do {
                          res.appendCodePoint(c);
                          c = snext();
                  } while (!isEndOfLine(c));
                  return res.toString();
          }

          public boolean isSpaceChar(int c)
          {
                  if (filter != null)
                          return filter.isSpaceChar(c);
                  return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
          }

          private boolean isEndOfLine(int c)
          {
                  return c == '\n' || c == '\r' || c == -1;
          }

          public interface SpaceCharFilter
          {
                  public boolean isSpaceChar(int ch);
          }

    }

    static int i()
    {
        return sc.nextInt();
    }
    static long l(){
        return sc.nextLong();
    }
    static int[] iarr(int n)
    {
        return sc.nextIntArray(n);
    }
    static long[] larr(int n)
    {
        return sc.nextLongArray(n);
    }
    static String s(){
        return sc.nextLine();
    }

 }

import java.util.*;
import java.io.*;
import java.math.*;
public class Main
{
    static class Reader
    {
        private InputStream mIs;private byte[] buf = new byte[1024];private int curChar,numChars;public Reader() { this(System.in); }public Reader(InputStream is) { mIs = is;}
        public int read() {if (numChars == -1) throw new InputMismatchException();if (curChar >= numChars) {curChar = 0;try { numChars = mIs.read(buf);} catch (IOException e) { throw new InputMismatchException();}if (numChars <= 0) return -1; }return buf[curChar++];}
        public String nextLine(){int c = read();while (isSpaceChar(c)) c = read();StringBuilder res = new StringBuilder();do {res.appendCodePoint(c);c = read();}while (!isEndOfLine(c));return res.toString() ;}
        public String s(){int c = read();while (isSpaceChar(c)) c = read();StringBuilder res = new StringBuilder();do {res.appendCodePoint(c);c = read();}while (!isSpaceChar(c));return res.toString();}
        public long l(){int c = read();while (isSpaceChar(c)) c = read();int sgn = 1;if (c == '-') { sgn = -1 ; c = read() ; }long res = 0; do{ if (c < '0' || c > '9') throw new InputMismatchException();res *= 10 ; res += c - '0' ; c = read();}while(!isSpaceChar(c));return res * sgn;}
        public int i(){int c = read() ;while (isSpaceChar(c)) c = read();int sgn = 1;if (c == '-') { sgn = -1 ; c = read() ; }int res = 0;do{if (c < '0' || c > '9') throw new InputMismatchException();res *= 10 ; res += c - '0' ; c = read() ;}while(!isSpaceChar(c));return res * sgn;}
        public double d() throws IOException {return Double.parseDouble(s()) ;}
        public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; }
        public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; }
        public int[] arr(int n){int[] ret = new int[n];for (int i = 0; i < n; i++) {ret[i] = i();}return ret;}
    }

           //       |----|       /\      |    |   -----   |
           //       |   /       /  \     |    |     |     |
           //       |--/       /----\    |----|     |     |
           //       |   \     /      \   |    |     |     |
           //       |    \   /        \  |    |   -----   -------

    public static void main(String[] args)throws IOException
    {
        Reader sc=new Reader();
        PrintWriter out=new PrintWriter(System.out);
        int n=sc.i();
        int m=sc.i();
        long arr[]=new long[n];
        for(int i=0;i<n;i++)arr[i]=sc.l();
        TreeSet<Long> ts1=new TreeSet<>();
        TreeSet<Long> ts2=new TreeSet<>();
        for(int bit=1;bit<(1<<(n/2));bit++)
        {
            long sum=0;
            for(int i=0;i<n/2;i++)
            {
                if((bit&(1<<i))>0)
                sum+=arr[i];
            }
            ts1.add(sum%m);
        }
        for(int bit=1;bit<(1<<(n-n/2));bit++)
        {
            long sum=0;
            for(int i=n/2+1;i<n;i++)
            {
                if((bit&(1<<(i-n/2-1)))>0)
                sum+=arr[i];
            }
            ts2.add(sum%m);
        }
        long max=0;
        for(long i:ts1)
        {
            long val1=0,val2=0;
            if(ts2.lower(m-i)!=null)
            val1=ts2.lower(m-i);
            max=Math.max((i+val1)%m,max);
            max=Math.max(max,(i+ts2.last())%m);
        }
        out.println(max);
        out.flush();
    }
}

import java.util.Scanner;
import java.util.TreeSet;

public class E {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner in = new Scanner(System.in);
		TreeSet<Integer> set = new TreeSet();
		set.add(1);
		set.add(2);
		int n = in.nextInt();
		int m = in.nextInt();
		int[] a = new int[n];
		for (int i = 0; i < a.length; i++) {
			a[i] = in.nextInt();
		}
		if (n == 1) {
			System.out.println(a[0] % m);
			return;
		}
		TreeSet<Integer> b = new TreeSet<>();
		b.add(0);
		for (int i = 0; i <= n / 2; i++) {
			TreeSet<Integer> b1 = new TreeSet<>();
			for (int l : b) {
				b1.add(l);
				b1.add((l + a[i]) % m);
			}
			b = b1;
		}
		TreeSet<Integer> c = new TreeSet<>();
		c.add(0);
		for (int i = n / 2 + 1; i < a.length; i++) {
			TreeSet<Integer> c1 = new TreeSet<>();
			for (int l : c) {
				c1.add(l);
				c1.add((l + a[i]) % m);
			}
			c = c1;
		}
		if (b.contains(m - 1)) {
			System.out.println(m - 1);
			return;
		}
		int ans = 0;
		for (int l : b) {
			ans = Math.max(ans, (ans + c.last()) % m);
			ans = Math.max(ans, c.floor(m - 1 - l));
		}
		System.out.println(ans);
	}

}

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class P888E {
    private static class HpReader {
        private BufferedReader in;
        private String containingDirPath;

        public HpReader(String dir, String inFile, String outFile) {
            initAndRedirectInOut(dir, inFile, outFile);
        }

        private static int ivl(String val) {
            return Integer.parseInt(val);
        }

        private void initAndRedirectInOut(String dir, String inFile, String outFile) {
            if (dir != null) {
                try {
                    containingDirPath = dir.endsWith(File.separator) ? dir : dir + File.separator;
                    if (isDebug && inFile != null) System.setIn(new FileInputStream(new File(containingDirPath + inFile)));
                    if (isDebug && outFile != null) System.setOut(new PrintStream(new File(containingDirPath + outFile)));
                } catch (FileNotFoundException e) {
                    // Do nothing, stdin & stdout are not redirected
                }
            }
            in = new BufferedReader(new InputStreamReader(System.in));
            out = new PrintWriter(System.out);
        }

        private String nextSingleStr() throws IOException {
            return in.readLine();
        }

        private String[] nextLineStr() throws IOException {
            return nextLineStr(0);
        }

        private String[] nextLineStr(int offset) throws IOException {
            String[] inp = nextSingleStr().split(" ");
            String[] rs = new String[offset + inp.length];
            System.arraycopy(inp, 0, rs, offset, inp.length);
            return rs;
        }

        private int nextSingleInt() throws IOException {
            return ivl(in.readLine());
        }

        private int[] nextLineInt() throws IOException {
            return nextLineInt(0);
        }

        private int[] nextLineInt(int offset) throws IOException {
            String[] inp = nextLineStr();
            int[] rs = new int[offset + inp.length];
            for (int i = 0; i < inp.length; i++) rs[offset + i] = ivl(inp[i]);
            return rs;
        }

        private int[][] nextMatInt(int lineCount) throws IOException {
            return nextMatInt(lineCount, 0, 0);
        }

        private int[][] nextMatInt(int lineCount, int rowOffset, int colOffset) throws IOException {
            int[][] rs = new int[rowOffset + lineCount][];
            for (int i = rowOffset; i < rs.length; i++) rs[i] = nextLineInt(colOffset);
            return rs;
        }
    }

    private static class HpHelper {
        private static final String LOCAL_DEBUG_FLAG = "COM_PROG_DEBUG";

        private static boolean isDebug() {
            try {
                return Boolean.parseBoolean(System.getenv(HpHelper.LOCAL_DEBUG_FLAG));
            } catch (Exception e) {
                return false;
            }
        }

        private static String createDelimiter(String delimiter) {
            return delimiter == null ? " " : delimiter;
        }

        private static void println(int[] data, String delimiter) {
            delimiter = createDelimiter(delimiter);
            for (int t : data) out.print(t + delimiter);
            out.println();
        }

        private static void println(long[] data, String delimiter) {
            delimiter = createDelimiter(delimiter);
            for (long t : data) out.print(t + delimiter);
            out.println();
        }

        private static <T> void println(T[] data, String delimiter) {
            delimiter = createDelimiter(delimiter);
            for (T t : data) {
                if (t instanceof int[]) {
                    println((int[]) t, delimiter);
                } else if (t instanceof long[]) {
                    println((long[]) t, delimiter);
                } else if (t instanceof Object[]) {
                    println((Object[]) t, delimiter);
                } else {
                    out.print(t + delimiter);
                }
            }
            out.println();
        }
    }

    private static boolean isDebug = HpHelper.isDebug();
    private static HpReader in = new HpReader("/Users/apple/Work/WorkSpaces/CompetitiveProg/", "in.txt", null);
    private static PrintWriter out;

    private static void calRem(int[] data, int lv, List<Integer> target, int carried, int mod) {
        if (lv >= data.length) {
            target.add(carried);
            return;
        }

        calRem(data, lv + 1, target, carried % mod, mod);
        calRem(data, lv + 1, target, (carried % mod + data[lv] % mod) % mod, mod);
    }

    public static void main(String[] args) throws IOException {
        int[] inp = in.nextLineInt();
        int n = inp[0], m = inp[1], rs = 0;
        int[] data = in.nextLineInt();
        int[] dt1 = Arrays.copyOfRange(data, 0, n / 2), dt2 = Arrays.copyOfRange(data, n / 2, n);
        List<Integer> l1 = new ArrayList<>(1 << dt1.length), l2 = new ArrayList<>(1 << dt2.length);

        calRem(dt1, 0, l1, 0, m);
        calRem(dt2, 0, l2, 0, m);

        Collections.sort(l2);
        for (int i : l1) {
            int r = m - 1 - i;
            int pos = Collections.binarySearch(l2, r), toAdd = -1;
            if (pos < 0) {
                pos = -pos - 1;
                if (pos >= l2.size()) {
                    pos = l2.size() - 1;
                    toAdd = l2.get(pos);
                } else {
                    if (pos == 0) {
                        toAdd = 0;
                    } else {
                        toAdd = l2.get(pos);
                    }
                }
            } else {
                toAdd = l2.get(pos);
            }
            rs = Math.max(rs, (i + toAdd) % m);
        }
        out.println(rs);

        out.flush();
    }
}

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class P888E {
    private static class HpReader {
        private BufferedReader in;
        private String containingDirPath;

        public HpReader(String dir, String inFile, String outFile) {
            initAndRedirectInOut(dir, inFile, outFile);
        }

        private static int ivl(String val) {
            return Integer.parseInt(val);
        }

        private void initAndRedirectInOut(String dir, String inFile, String outFile) {
            if (dir != null) {
                try {
                    containingDirPath = dir.endsWith(File.separator) ? dir : dir + File.separator;
                    if (isDebug && inFile != null) System.setIn(new FileInputStream(new File(containingDirPath + inFile)));
                    if (isDebug && outFile != null) System.setOut(new PrintStream(new File(containingDirPath + outFile)));
                } catch (FileNotFoundException e) {
                    // Do nothing, stdin & stdout are not redirected
                }
            }
            in = new BufferedReader(new InputStreamReader(System.in));
            out = new PrintWriter(System.out);
        }

        private String nextSingleStr() throws IOException {
            return in.readLine();
        }

        private String[] nextLineStr() throws IOException {
            return nextLineStr(0);
        }

        private String[] nextLineStr(int offset) throws IOException {
            String[] inp = nextSingleStr().split(" ");
            String[] rs = new String[offset + inp.length];
            System.arraycopy(inp, 0, rs, offset, inp.length);
            return rs;
        }

        private int nextSingleInt() throws IOException {
            return ivl(in.readLine());
        }

        private int[] nextLineInt() throws IOException {
            return nextLineInt(0);
        }

        private int[] nextLineInt(int offset) throws IOException {
            String[] inp = nextLineStr();
            int[] rs = new int[offset + inp.length];
            for (int i = 0; i < inp.length; i++) rs[offset + i] = ivl(inp[i]);
            return rs;
        }

        private int[][] nextMatInt(int lineCount) throws IOException {
            return nextMatInt(lineCount, 0, 0);
        }

        private int[][] nextMatInt(int lineCount, int rowOffset, int colOffset) throws IOException {
            int[][] rs = new int[rowOffset + lineCount][];
            for (int i = rowOffset; i < rs.length; i++) rs[i] = nextLineInt(colOffset);
            return rs;
        }
    }

    private static class HpHelper {
        private static final String LOCAL_DEBUG_FLAG = "COM_PROG_DEBUG";

        private static boolean isDebug() {
            try {
                return Boolean.parseBoolean(System.getenv(HpHelper.LOCAL_DEBUG_FLAG));
            } catch (Exception e) {
                return false;
            }
        }

        private static String createDelimiter(String delimiter) {
            return delimiter == null ? " " : delimiter;
        }

        private static void println(int[] data, String delimiter) {
            delimiter = createDelimiter(delimiter);
            for (int t : data) out.print(t + delimiter);
            out.println();
        }

        private static void println(long[] data, String delimiter) {
            delimiter = createDelimiter(delimiter);
            for (long t : data) out.print(t + delimiter);
            out.println();
        }

        private static <T> void println(T[] data, String delimiter) {
            delimiter = createDelimiter(delimiter);
            for (T t : data) {
                if (t instanceof int[]) {
                    println((int[]) t, delimiter);
                } else if (t instanceof long[]) {
                    println((long[]) t, delimiter);
                } else if (t instanceof Object[]) {
                    println((Object[]) t, delimiter);
                } else {
                    out.print(t + delimiter);
                }
            }
            out.println();
        }
    }

    private static boolean isDebug = HpHelper.isDebug();
    private static HpReader in = new HpReader("/Users/apple/Work/WorkSpaces/CompetitiveProg/", "in.txt", null);
    private static PrintWriter out;

    private static void calRem(int[] data, int lv, List<Integer> target, int carried, int mod) {
        if (lv >= data.length) {
            target.add(carried);
            return;
        }

        calRem(data, lv + 1, target, carried % mod, mod);
        calRem(data, lv + 1, target, (carried % mod + data[lv] % mod) % mod, mod);
    }

    public static void main(String[] args) throws IOException {
        int[] inp = in.nextLineInt();
        int n = inp[0], m = inp[1], rs = 0;
        int[] data = in.nextLineInt();
        int[] dt1 = Arrays.copyOfRange(data, 0, n / 2), dt2 = Arrays.copyOfRange(data, n / 2, n);
        List<Integer> l1 = new ArrayList<>(1 << dt1.length), l2 = new ArrayList<>(1 << dt2.length);

        calRem(dt1, 0, l1, 0, m);
        calRem(dt2, 0, l2, 0, m);

        Collections.sort(l2);
        for (int i : l1) {
            int r = m - 1 - i;
            int pos = Collections.binarySearch(l2, r);
            if (pos < 0) {
                pos = -pos - 1;
                if (pos >= l2.size()) {
                    pos = l2.size() - 1;
                }
            }
            rs = Math.max(rs, (i + l2.get(pos)) % m);
        }
        out.println(rs);

        out.flush();
    }
}

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

public class Main{
class Node {
    int id;
    long mask;
    public Node(int id,long mask){
        this.id=id;
        this.mask=mask;

    }

    public boolean equals(Object o){
        Node c=(Node)o;
        return id==c.id && mask==c.mask;

    }
}
    void solve() {
        int n=ni();
        M=nl();
        a=new long[n+1];
        for(int i=1;i<=n;i++) a[i]=nl()%M;
        pow=new long[n+1];
        pow[0]=1;
        for(int i=1;i<=n;i++) pow[i]=(pow[i-1]*2);
        long ans=go(1,0,n);
        pw.println(ans);
    }
    long a[];
    long pow[];
    HashMap<Node,Long> mp=new HashMap<>();
    long go(int i,long mask,int n){
        if(i>n){
            return 0;
        }
        if(mp.containsKey(new Node(i,mask))) return mp.get(new Node(i,mask));
        long cc=go(i+1,mask,n);
        cc=Math.max(cc,(a[i]+go(i+1,mask+pow[i-1],n))%M );
        mp.put(new Node(i,mask),cc);
        return cc;
    }

    long M=(long)1e9+7;
    InputStream is;
    PrintWriter pw;
    String INPUT = "";
    void run() throws Exception {
        is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
        pw = new PrintWriter(System.out);
        long s = System.currentTimeMillis();
        solve();
        pw.flush();
        if(!INPUT.isEmpty())tr(System.currentTimeMillis()-s+"ms");
    }

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

    private byte[] inbuf = new byte[1024];
    public int lenbuf = 0, ptrbuf = 0;

    private int readByte() {
        if(lenbuf == -1)throw new InputMismatchException();
        if(ptrbuf >= lenbuf){
            ptrbuf = 0;
            try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
            if(lenbuf <= 0)return -1;
        }
        return inbuf[ptrbuf++];
    }

    private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
    private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }

    private double nd() { return Double.parseDouble(ns()); }
    private char nc() { return (char)skip(); }

    private String ns() {
        int b = skip();
        StringBuilder sb = new StringBuilder();
        while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
            sb.appendCodePoint(b);
            b = readByte();
        }
        return sb.toString();
    }

    private char[] ns(int n) {
        char[] buf = new char[n];
        int b = skip(), p = 0;
        while(p < n && !(isSpaceChar(b))){
            buf[p++] = (char)b;
            b = readByte();
        }
        return n == p ? buf : Arrays.copyOf(buf, p);
    }

    private char[][] nm(int n, int m) {
        char[][] map = new char[n][];
        for(int i = 0;i < n;i++)map[i] = ns(m);
        return map;
    }

    private int[] na(int n) {
        int[] a = new int[n];
        for(int i = 0;i < n;i++)a[i] = ni();
        return a;
    }

    private int ni() {
        int num = 0, b;
        boolean minus = false;
        while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
        if(b == '-'){
            minus = true;
            b = readByte();
        }

        while(true){
            if(b >= '0' && b <= '9'){
                num = num * 10 + (b - '0');
            }else{
                return minus ? -num : num;
            }
            b = readByte();
        }
    }

    private long nl() {
        long num = 0;
        int b;
        boolean minus = false;
        while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
        if(b == '-'){
            minus = true;
            b = readByte();
        }

        while(true){
            if(b >= '0' && b <= '9'){
                num = num * 10 + (b - '0');
            }else{
                return minus ? -num : num;
            }
            b = readByte();
        }
    }

    private void tr(Object... o) { if(INPUT.length() > 0)System.out.println(Arrays.deepToString(o)); }
}

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

public class E888 {

	int n;
	long m;
	int l;
	int r;

	private void solve() throws Exception {
		n = nextInt();
		m = nextInt();
		l = n/2;
		r = n-l;
		long[] al = new long[l];
		for(int i = 0; i < l; i++) al[i] = nextLong()%m;
		long[] ar = new long[r];
		for(int i = 0; i < r; i++) ar[i] = nextLong()%m;
		long[] part1 = doit(al);
		long[] part2 = doit(ar);
		long best = 0;
		for(int i = 0; i < part1.length; i++){
			int left = 0;
			int right = r;
			while(left < right-1) {
				int mid = (left+right)/2;
				if(part1[i] + part2[mid] < m) left = mid;
				else right = mid;
			}
			best = Math.max(best, (part1[i]+part2[left])%m);
			left = Math.min(r-1, right+1);
			right = r;
			while(left < right-1) {
				int mid = (left+right)/2;
				if(part1[i] + part2[mid] < 2*m) left = mid;
				else right = mid;
			}
			best = Math.max(best, (part1[i]+part2[left])%m);
		}
		out.println(best);
	}

	long[] doit(long[] a) {
		int n = a.length;
		long[] res = new long[(1<<n)];
		for(int i = 0; i < (1<<n); i++) {
			int ii = i;
			for(int j = 0; j < n; j++, ii >>= 1) if(ii%2 == 1) res[i] = (res[i]+a[j])%m;
		}
		Arrays.sort(res);
		return res;
	}

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

	private BufferedReader in;
	private PrintWriter out;
	private StringTokenizer tokenizer;

	public void run() {
		try {
			in = new BufferedReader(new InputStreamReader(System.in));
			tokenizer = null;
			out = new PrintWriter(System.out);
			solve();
			in.close();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(1);
		}
	}

	private int nextInt() throws IOException {
		return Integer.parseInt(nextToken());
	}

	private long nextLong() throws IOException {
		return Long.parseLong(nextToken());
	}

	private float nextFloat() throws IOException {
		return Float.parseFloat(nextToken());
	}

	private String nextLine() throws IOException {
		return new String(in.readLine());
	}

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

}

import java.io.*;
import java.util.*;
import java.util.Map.Entry;
import java.lang.Math;
import java.math.BigInteger;

public class Problem {

	void solve() throws IOException {

		int n = rI();
		if(n%2==1){
			n++;
		}
		int m = rI();
		int[] a = new int[n];
		for(int i=0;i<n-1;++i){
			a[i] = rI();
		}
		a[n-1] = m;
		TreeSet<Integer> st1 = new TreeSet<>();
		TreeSet<Integer> st2 = new TreeSet<>();
		for (int mask = 0; mask < binPow(2, n/2); ++mask) {
			int sum = 0;
			for (int bit = 0; bit < (int) Math.pow(2, Math.min(n / 2, 17)); ++bit) {
				if (checkBit(mask, bit) == 1) {
					sum = (sum + a[bit] % m) % m;
				}
			}
			st1.add(sum);
		}

		for (int mask = 0; mask < binPow(2, n/2); ++mask) {
			int sum = 0;
			for (int bit = 0; bit < n/2 ; ++bit) {
				if (checkBit(mask, bit) == 1) {
					sum = (sum + a[n/2+bit] % m) % m;
				}
			}
			st2.add(sum);
		}

		int ans = 0;
		for(int i: st1){
			if(st2.lower(m-i)!=null){
				ans = Math.max(ans, i+st2.lower(m-i));
			}
		}
		out.println(ans);
	}

	class SegmentTree {
		int[] t;

		SegmentTree(int[] a, int n) {
			t = new int[4 * n];
			build(a, 1, 1, n);
		}

		void build(int[] a, int v, int tl, int tr) {
			if (tl == tr) {
				t[v] = a[tl];
				return;
			}

			int tm = (tl + tr) / 2;
			build(a, 2 * v, tl, tm);
			build(a, 2 * v + 1, tm + 1, tr);
			t[v] = Math.min(t[2 * v], t[2 * v + 1]);
		}

		void update(int v, int tl, int tr, int pos, int value) {
			if (tl == tr) {
				t[v] = value;
				return;
			}
			int tm = (tl + tr) / 2;
			if (pos <= tm) {
				update(2 * v, tl, tm, pos, value);
			} else {
				update(2 * v + 1, tm + 1, tr, pos, value);
			}

			t[v] = Math.min(t[2 * v], t[2 * v + 1]);
		}

		int getMin(int v, int tl, int tr, int l, int r) {
			if (l > r) {
				return INF;
			}
			if (tl == l && tr == r) {
				return t[v];
			}

			int tm = (tl + tr) / 2;

			int min1 = getMin(2 * v, tl, tm, l, Math.min(tm, r));
			int min2 = getMin(2 * v + 1, tm + 1, tr, Math.max(l, tm + 1), r);

			return Math.min(min1, min2);
		}
	}

	int checkBit(int mask, int bit) {
		return (mask >> bit) & 1;
	}

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

		new Problem().run();
	}

	boolean isLower(char a) {
		return ((int) a) >= 97 ? true : false;
	}

	int INF = Integer.MAX_VALUE - 12345;

	int[][] STEPS = { { 0, 1 }, { 1, 0 }, { -1, 0 }, { 0, -1 } };

	BufferedReader in;
	PrintWriter out;
	StringTokenizer tok;
	Random rnd = new Random();
	static final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;

	Problem() throws FileNotFoundException {

		try {
			in = new BufferedReader(new FileReader("input.txt"));
			out = new PrintWriter("output.txt");
		} catch (Exception e) {
			in = new BufferedReader(new InputStreamReader(System.in));
			out = new PrintWriter(System.out);
		}

		tok = new StringTokenizer("");
	}

	long checkBit(long mask, int bit) {
		return (mask >> bit) & 1;
	}

	// ======================================================

	// ======================================================
	void run() throws IOException {
		solve();
		out.close();
	}

	char[] reverseCharArray(char[] arr) {
		char[] ans = new char[arr.length];
		for (int i = 0; i < arr.length; ++i) {
			ans[i] = arr[arr.length - i - 1];
		}
		return ans;
	}

	int sqrt(double m) {
		int l = 0;
		int r = 1000000000 + 9;
		int i = 1000;
		while (r - l > 1) {
			int mid = (r + l) / 2;
			if (mid * mid > m) {
				r = mid;
			} else {
				l = mid;
			}
		}
		return l;
	}

	int countPow(int m, int n) {
		int ans = 0;
		while (m % n == 0 && m > 0) {
			ans++;
			m /= n;
		}
		return ans;
	}

	long binPow(long a, long b) {
		if (b == 0) {
			return 1;
		}
		if (b % 2 == 1) {
			return a * binPow(a, b - 1);
		} else {
			long c = binPow(a, b / 2);
			return c * c;
		}

	}

	int gcd(int a, int b) {
		return b == 0 ? a : gcd(b, a % b);
	}

	long pow(long x, long k) {
		long ans = 1;
		for (int i = 0; i < k; ++i) {
			ans *= x;
		}
		return ans;
	}

	class Fenwik {
		private long[] t;
		private int length;

		Fenwik(int[] a) {
			this.length = a.length + 100;
			this.t = new long[length];
			for (int i = 0; i < a.length; ++i) {
				this.inc(i, a[i]);
			}
		}

		void inc(int i, int delta) {
			for (; i < this.length; i = i | (i + 1)) {
				this.t[i] += delta;
			}
		}

		long getSum(int r) {
			long sum = 0;

			for (; r >= 0; r = (r & (r + 1)) - 1) {
				sum += this.t[r];
			}

			return sum;
		}
	}

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

	String delimiter = " ";

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

	String rS() throws IOException {
		while (!tok.hasMoreTokens()) {
			String nextLine = readLine();
			if (null == nextLine)
				return null;

			tok = new StringTokenizer(nextLine);
		}

		return tok.nextToken(delimiter);
	}

	int rI() throws IOException {
		return Integer.parseInt(rS());
	}

	long rL() throws IOException {
		return Long.parseLong(rS());
	}

	double rD() throws IOException {
		return Double.parseDouble(rS());
	}

	int[] rA(int b) {
		int a[] = new int[b];
		for (int i = 0; i < b; i++) {
			try {
				a[i] = rI();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return a;
	}

	int[] readSortedIntArray(int size) throws IOException {
		Integer[] array = new Integer[size];

		for (int index = 0; index < size; ++index) {
			array[index] = rI();
		}
		Arrays.sort(array);

		int[] sortedArray = new int[size];
		for (int index = 0; index < size; ++index) {
			sortedArray[index] = array[index];
		}

		return sortedArray;
	}

	int[] sortedIntArray(int size, int[] array) throws IOException {
		for (int index = 0; index < size; ++index) {
			array[index] = rI();
		}
		Arrays.sort(array);

		int[] sortedArray = new int[size];
		for (int index = 0; index < size; ++index) {
			sortedArray[index] = array[index];
		}

		return sortedArray;
	}
}

import java.io.*;
import java.util.*;
import java.util.Map.Entry;
import java.lang.Math;
import java.math.BigInteger;

public class Problem {

	void solve() throws IOException {

		int n = rI();
		int m = rI();
		ArrayList<Long> a = new ArrayList<>();
		long sum = 0;

		for (int i = 0; i < n; ++i) {
			a.add(rL());
			sum = (sum + a.get(i)) % m;
			;
		}
		long ans = 0;
		Collections.shuffle(a);

		for (int i = 1; i <= (int) Math.pow(2, Math.min(18, n)); ++i) {
			long curAns = 0;
			for (int bit = 0; bit < Math.min(18, n); ++bit) {
				if (checkBit(i, bit) == 1) {
					curAns = (curAns + a.get(bit)) % m;
				}
			}
			ans = Math.max(curAns, ans);
		}

		for (int i = 1; i <= (int) Math.pow(2, Math.min(18, n)); ++i) {
			long curAns = sum;
			for (int bit = 0; bit < Math.min(20, n); ++bit) {
				if (checkBit(i, bit) == 1) {
					curAns = (curAns - a.get(bit) % m + m) % m;
				}
			}
			ans = Math.max(curAns, ans);
		}

		out.println(ans);
	}

	class SegmentTree {
		int[] t;

		SegmentTree(int[] a, int n) {
			t = new int[4 * n];
			build(a, 1, 1, n);
		}

		void build(int[] a, int v, int tl, int tr) {
			if (tl == tr) {
				t[v] = a[tl];
				return;
			}

			int tm = (tl + tr) / 2;
			build(a, 2 * v, tl, tm);
			build(a, 2 * v + 1, tm + 1, tr);
			t[v] = Math.min(t[2 * v], t[2 * v + 1]);
		}

		void update(int v, int tl, int tr, int pos, int value) {
			if (tl == tr) {
				t[v] = value;
				return;
			}
			int tm = (tl + tr) / 2;
			if (pos <= tm) {
				update(2 * v, tl, tm, pos, value);
			} else {
				update(2 * v + 1, tm + 1, tr, pos, value);
			}

			t[v] = Math.min(t[2 * v], t[2 * v + 1]);
		}

		int getMin(int v, int tl, int tr, int l, int r) {
			if (l > r) {
				return INF;
			}
			if (tl == l && tr == r) {
				return t[v];
			}

			int tm = (tl + tr) / 2;

			int min1 = getMin(2 * v, tl, tm, l, Math.min(tm, r));
			int min2 = getMin(2 * v + 1, tm + 1, tr, Math.max(l, tm + 1), r);

			return Math.min(min1, min2);
		}
	}

	int checkBit(int mask, int bit) {
		return (mask >> bit) & 1;
	}

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

		new Problem().run();
	}

	boolean isLower(char a) {
		return ((int) a) >= 97 ? true : false;
	}

	int INF = Integer.MAX_VALUE - 12345;

	int[][] STEPS = { { 0, 1 }, { 1, 0 }, { -1, 0 }, { 0, -1 } };

	BufferedReader in;
	PrintWriter out;
	StringTokenizer tok;
	Random rnd = new Random();
	static final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;

	Problem() throws FileNotFoundException {

		try {
			in = new BufferedReader(new FileReader("input.txt"));
			out = new PrintWriter("output.txt");
		} catch (Exception e) {
			in = new BufferedReader(new InputStreamReader(System.in));
			out = new PrintWriter(System.out);
		}

		tok = new StringTokenizer("");
	}

	long checkBit(long mask, int bit) {
		return (mask >> bit) & 1;
	}

	// ======================================================

	// ======================================================
	void run() throws IOException {
		solve();
		out.close();
	}

	char[] reverseCharArray(char[] arr) {
		char[] ans = new char[arr.length];
		for (int i = 0; i < arr.length; ++i) {
			ans[i] = arr[arr.length - i - 1];
		}
		return ans;
	}

	int sqrt(double m) {
		int l = 0;
		int r = 1000000000 + 9;
		int i = 1000;
		while (r - l > 1) {
			int mid = (r + l) / 2;
			if (mid * mid > m) {
				r = mid;
			} else {
				l = mid;
			}
		}
		return l;
	}

	int countPow(int m, int n) {
		int ans = 0;
		while (m % n == 0 && m > 0) {
			ans++;
			m /= n;
		}
		return ans;
	}

	long binPow(long a, long b) {
		if (b == 0) {
			return 1;
		}
		if (b % 2 == 1) {
			return a * binPow(a, b - 1);
		} else {
			long c = binPow(a, b / 2);
			return c * c;
		}

	}

	int gcd(int a, int b) {
		return b == 0 ? a : gcd(b, a % b);
	}

	long pow(long x, long k) {
		long ans = 1;
		for (int i = 0; i < k; ++i) {
			ans *= x;
		}
		return ans;
	}

	class Fenwik {
		private long[] t;
		private int length;

		Fenwik(int[] a) {
			this.length = a.length + 100;
			this.t = new long[length];
			for (int i = 0; i < a.length; ++i) {
				this.inc(i, a[i]);
			}
		}

		void inc(int i, int delta) {
			for (; i < this.length; i = i | (i + 1)) {
				this.t[i] += delta;
			}
		}

		long getSum(int r) {
			long sum = 0;

			for (; r >= 0; r = (r & (r + 1)) - 1) {
				sum += this.t[r];
			}

			return sum;
		}
	}

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

	String delimiter = " ";

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

	String rS() throws IOException {
		while (!tok.hasMoreTokens()) {
			String nextLine = readLine();
			if (null == nextLine)
				return null;

			tok = new StringTokenizer(nextLine);
		}

		return tok.nextToken(delimiter);
	}

	int rI() throws IOException {
		return Integer.parseInt(rS());
	}

	long rL() throws IOException {
		return Long.parseLong(rS());
	}

	double rD() throws IOException {
		return Double.parseDouble(rS());
	}

	int[] rA(int b) {
		int a[] = new int[b];
		for (int i = 0; i < b; i++) {
			try {
				a[i] = rI();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return a;
	}

	int[] readSortedIntArray(int size) throws IOException {
		Integer[] array = new Integer[size];

		for (int index = 0; index < size; ++index) {
			array[index] = rI();
		}
		Arrays.sort(array);

		int[] sortedArray = new int[size];
		for (int index = 0; index < size; ++index) {
			sortedArray[index] = array[index];
		}

		return sortedArray;
	}

	int[] sortedIntArray(int size, int[] array) throws IOException {
		for (int index = 0; index < size; ++index) {
			array[index] = rI();
		}
		Arrays.sort(array);

		int[] sortedArray = new int[size];
		for (int index = 0; index < size; ++index) {
			sortedArray[index] = array[index];
		}

		return sortedArray;
	}
}

import java.io.*;
import java.util.*;
import java.util.Map.Entry;
import java.lang.Math;
import java.math.BigInteger;

public class Problem {

	void solve() throws IOException {

		int n = rI();
		int m = rI();
		ArrayList<Long> a = new ArrayList<>();
		long sum = 0;

		for (int i = 0; i < n; ++i) {
			a.add(rL());
			sum = (sum + a.get(i)) % m;
			;
		}
		long ans = 0;
		Collections.shuffle(a);

		for (int i = 1; i <= (int) Math.pow(2, Math.min(18, n)); ++i) {
			long curAns = 0;
			for (int bit = 0; bit < Math.min(18, n); ++bit) {
				if (checkBit(i, bit) == 1) {
					curAns = (curAns + a.get(bit)) % m;
				}
			}
			ans = Math.max(curAns, ans);
		}
		Collections.shuffle(a);
		for (int i = 1; i <= (int) Math.pow(2, Math.min(18, n)); ++i) {
			long curAns = sum;
			for (int bit = 0; bit < Math.min(20, n); ++bit) {
				if (checkBit(i, bit) == 1) {
					curAns = (curAns - a.get(bit) % m + m) % m;
				}
			}
			ans = Math.max(curAns, ans);
		}

		out.println(ans);
	}

	class SegmentTree {
		int[] t;

		SegmentTree(int[] a, int n) {
			t = new int[4 * n];
			build(a, 1, 1, n);
		}

		void build(int[] a, int v, int tl, int tr) {
			if (tl == tr) {
				t[v] = a[tl];
				return;
			}

			int tm = (tl + tr) / 2;
			build(a, 2 * v, tl, tm);
			build(a, 2 * v + 1, tm + 1, tr);
			t[v] = Math.min(t[2 * v], t[2 * v + 1]);
		}

		void update(int v, int tl, int tr, int pos, int value) {
			if (tl == tr) {
				t[v] = value;
				return;
			}
			int tm = (tl + tr) / 2;
			if (pos <= tm) {
				update(2 * v, tl, tm, pos, value);
			} else {
				update(2 * v + 1, tm + 1, tr, pos, value);
			}

			t[v] = Math.min(t[2 * v], t[2 * v + 1]);
		}

		int getMin(int v, int tl, int tr, int l, int r) {
			if (l > r) {
				return INF;
			}
			if (tl == l && tr == r) {
				return t[v];
			}

			int tm = (tl + tr) / 2;

			int min1 = getMin(2 * v, tl, tm, l, Math.min(tm, r));
			int min2 = getMin(2 * v + 1, tm + 1, tr, Math.max(l, tm + 1), r);

			return Math.min(min1, min2);
		}
	}

	int checkBit(int mask, int bit) {
		return (mask >> bit) & 1;
	}

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

		new Problem().run();
	}

	boolean isLower(char a) {
		return ((int) a) >= 97 ? true : false;
	}

	int INF = Integer.MAX_VALUE - 12345;

	int[][] STEPS = { { 0, 1 }, { 1, 0 }, { -1, 0 }, { 0, -1 } };

	BufferedReader in;
	PrintWriter out;
	StringTokenizer tok;
	Random rnd = new Random();
	static final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;

	Problem() throws FileNotFoundException {

		try {
			in = new BufferedReader(new FileReader("input.txt"));
			out = new PrintWriter("output.txt");
		} catch (Exception e) {
			in = new BufferedReader(new InputStreamReader(System.in));
			out = new PrintWriter(System.out);
		}

		tok = new StringTokenizer("");
	}

	long checkBit(long mask, int bit) {
		return (mask >> bit) & 1;
	}

	// ======================================================

	// ======================================================
	void run() throws IOException {
		solve();
		out.close();
	}

	char[] reverseCharArray(char[] arr) {
		char[] ans = new char[arr.length];
		for (int i = 0; i < arr.length; ++i) {
			ans[i] = arr[arr.length - i - 1];
		}
		return ans;
	}

	int sqrt(double m) {
		int l = 0;
		int r = 1000000000 + 9;
		int i = 1000;
		while (r - l > 1) {
			int mid = (r + l) / 2;
			if (mid * mid > m) {
				r = mid;
			} else {
				l = mid;
			}
		}
		return l;
	}

	int countPow(int m, int n) {
		int ans = 0;
		while (m % n == 0 && m > 0) {
			ans++;
			m /= n;
		}
		return ans;
	}

	long binPow(long a, long b) {
		if (b == 0) {
			return 1;
		}
		if (b % 2 == 1) {
			return a * binPow(a, b - 1);
		} else {
			long c = binPow(a, b / 2);
			return c * c;
		}

	}

	int gcd(int a, int b) {
		return b == 0 ? a : gcd(b, a % b);
	}

	long pow(long x, long k) {
		long ans = 1;
		for (int i = 0; i < k; ++i) {
			ans *= x;
		}
		return ans;
	}

	class Fenwik {
		private long[] t;
		private int length;

		Fenwik(int[] a) {
			this.length = a.length + 100;
			this.t = new long[length];
			for (int i = 0; i < a.length; ++i) {
				this.inc(i, a[i]);
			}
		}

		void inc(int i, int delta) {
			for (; i < this.length; i = i | (i + 1)) {
				this.t[i] += delta;
			}
		}

		long getSum(int r) {
			long sum = 0;

			for (; r >= 0; r = (r & (r + 1)) - 1) {
				sum += this.t[r];
			}

			return sum;
		}
	}

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

	String delimiter = " ";

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

	String rS() throws IOException {
		while (!tok.hasMoreTokens()) {
			String nextLine = readLine();
			if (null == nextLine)
				return null;

			tok = new StringTokenizer(nextLine);
		}

		return tok.nextToken(delimiter);
	}

	int rI() throws IOException {
		return Integer.parseInt(rS());
	}

	long rL() throws IOException {
		return Long.parseLong(rS());
	}

	double rD() throws IOException {
		return Double.parseDouble(rS());
	}

	int[] rA(int b) {
		int a[] = new int[b];
		for (int i = 0; i < b; i++) {
			try {
				a[i] = rI();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return a;
	}

	int[] readSortedIntArray(int size) throws IOException {
		Integer[] array = new Integer[size];

		for (int index = 0; index < size; ++index) {
			array[index] = rI();
		}
		Arrays.sort(array);

		int[] sortedArray = new int[size];
		for (int index = 0; index < size; ++index) {
			sortedArray[index] = array[index];
		}

		return sortedArray;
	}

	int[] sortedIntArray(int size, int[] array) throws IOException {
		for (int index = 0; index < size; ++index) {
			array[index] = rI();
		}
		Arrays.sort(array);

		int[] sortedArray = new int[size];
		for (int index = 0; index < size; ++index) {
			sortedArray[index] = array[index];
		}

		return sortedArray;
	}
}

import java.io.*;
import java.util.*;
import java.util.Map.Entry;
import java.lang.Math;
import java.math.BigInteger;

public class Problem {

	void solve() throws IOException {

		int n = rI();
		int m = rI();
		ArrayList<Long> a = new ArrayList<>();
		long sum = 0;

		for (int i = 0; i < n; ++i) {
			a.add(rL());
			sum = (sum + a.get(i)) % m;
			;
		}
		long ans = 0;

		for(int j=0;j<4;++j){
			Collections.shuffle(a);

			for (int i = 1; i <= (int) Math.pow(2, Math.min(18, n)); ++i) {
				long curAns = 0;
				for (int bit = 0; bit < Math.min(18, n); ++bit) {
					if (checkBit(i, bit) == 1) {
						curAns = (curAns + a.get(bit)) % m;
					}
				}
				ans = Math.max(curAns, ans);
			}
			Collections.shuffle(a);
			for (int i = 1; i <= (int) Math.pow(2, Math.min(18, n)); ++i) {
				long curAns = sum;
				for (int bit = 0; bit < Math.min(20, n); ++bit) {
					if (checkBit(i, bit) == 1) {
						curAns = (curAns - a.get(bit) % m + m) % m;
					}
				}
				ans = Math.max(curAns, ans);
			}
		}

		out.println(ans);
	}

	class SegmentTree {
		int[] t;

		SegmentTree(int[] a, int n) {
			t = new int[4 * n];
			build(a, 1, 1, n);
		}

		void build(int[] a, int v, int tl, int tr) {
			if (tl == tr) {
				t[v] = a[tl];
				return;
			}

			int tm = (tl + tr) / 2;
			build(a, 2 * v, tl, tm);
			build(a, 2 * v + 1, tm + 1, tr);
			t[v] = Math.min(t[2 * v], t[2 * v + 1]);
		}

		void update(int v, int tl, int tr, int pos, int value) {
			if (tl == tr) {
				t[v] = value;
				return;
			}
			int tm = (tl + tr) / 2;
			if (pos <= tm) {
				update(2 * v, tl, tm, pos, value);
			} else {
				update(2 * v + 1, tm + 1, tr, pos, value);
			}

			t[v] = Math.min(t[2 * v], t[2 * v + 1]);
		}

		int getMin(int v, int tl, int tr, int l, int r) {
			if (l > r) {
				return INF;
			}
			if (tl == l && tr == r) {
				return t[v];
			}

			int tm = (tl + tr) / 2;

			int min1 = getMin(2 * v, tl, tm, l, Math.min(tm, r));
			int min2 = getMin(2 * v + 1, tm + 1, tr, Math.max(l, tm + 1), r);

			return Math.min(min1, min2);
		}
	}

	int checkBit(int mask, int bit) {
		return (mask >> bit) & 1;
	}

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

		new Problem().run();
	}

	boolean isLower(char a) {
		return ((int) a) >= 97 ? true : false;
	}

	int INF = Integer.MAX_VALUE - 12345;

	int[][] STEPS = { { 0, 1 }, { 1, 0 }, { -1, 0 }, { 0, -1 } };

	BufferedReader in;
	PrintWriter out;
	StringTokenizer tok;
	Random rnd = new Random();
	static final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;

	Problem() throws FileNotFoundException {

		try {
			in = new BufferedReader(new FileReader("input.txt"));
			out = new PrintWriter("output.txt");
		} catch (Exception e) {
			in = new BufferedReader(new InputStreamReader(System.in));
			out = new PrintWriter(System.out);
		}

		tok = new StringTokenizer("");
	}

	long checkBit(long mask, int bit) {
		return (mask >> bit) & 1;
	}

	// ======================================================

	// ======================================================
	void run() throws IOException {
		solve();
		out.close();
	}

	char[] reverseCharArray(char[] arr) {
		char[] ans = new char[arr.length];
		for (int i = 0; i < arr.length; ++i) {
			ans[i] = arr[arr.length - i - 1];
		}
		return ans;
	}

	int sqrt(double m) {
		int l = 0;
		int r = 1000000000 + 9;
		int i = 1000;
		while (r - l > 1) {
			int mid = (r + l) / 2;
			if (mid * mid > m) {
				r = mid;
			} else {
				l = mid;
			}
		}
		return l;
	}

	int countPow(int m, int n) {
		int ans = 0;
		while (m % n == 0 && m > 0) {
			ans++;
			m /= n;
		}
		return ans;
	}

	long binPow(long a, long b) {
		if (b == 0) {
			return 1;
		}
		if (b % 2 == 1) {
			return a * binPow(a, b - 1);
		} else {
			long c = binPow(a, b / 2);
			return c * c;
		}

	}

	int gcd(int a, int b) {
		return b == 0 ? a : gcd(b, a % b);
	}

	long pow(long x, long k) {
		long ans = 1;
		for (int i = 0; i < k; ++i) {
			ans *= x;
		}
		return ans;
	}

	class Fenwik {
		private long[] t;
		private int length;

		Fenwik(int[] a) {
			this.length = a.length + 100;
			this.t = new long[length];
			for (int i = 0; i < a.length; ++i) {
				this.inc(i, a[i]);
			}
		}

		void inc(int i, int delta) {
			for (; i < this.length; i = i | (i + 1)) {
				this.t[i] += delta;
			}
		}

		long getSum(int r) {
			long sum = 0;

			for (; r >= 0; r = (r & (r + 1)) - 1) {
				sum += this.t[r];
			}

			return sum;
		}
	}

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

	String delimiter = " ";

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

	String rS() throws IOException {
		while (!tok.hasMoreTokens()) {
			String nextLine = readLine();
			if (null == nextLine)
				return null;

			tok = new StringTokenizer(nextLine);
		}

		return tok.nextToken(delimiter);
	}

	int rI() throws IOException {
		return Integer.parseInt(rS());
	}

	long rL() throws IOException {
		return Long.parseLong(rS());
	}

	double rD() throws IOException {
		return Double.parseDouble(rS());
	}

	int[] rA(int b) {
		int a[] = new int[b];
		for (int i = 0; i < b; i++) {
			try {
				a[i] = rI();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return a;
	}

	int[] readSortedIntArray(int size) throws IOException {
		Integer[] array = new Integer[size];

		for (int index = 0; index < size; ++index) {
			array[index] = rI();
		}
		Arrays.sort(array);

		int[] sortedArray = new int[size];
		for (int index = 0; index < size; ++index) {
			sortedArray[index] = array[index];
		}

		return sortedArray;
	}

	int[] sortedIntArray(int size, int[] array) throws IOException {
		for (int index = 0; index < size; ++index) {
			array[index] = rI();
		}
		Arrays.sort(array);

		int[] sortedArray = new int[size];
		for (int index = 0; index < size; ++index) {
			sortedArray[index] = array[index];
		}

		return sortedArray;
	}
}

import java.io.*;
import java.util.*;
import java.util.Map.Entry;
import java.lang.Math;
import java.math.BigInteger;

public class Problem {

	void solve() throws IOException {

		int n = rI();
		int m = rI();
		ArrayList<Long> a = new ArrayList<>();
		long sum = 0;

		for (int i = 0; i < n; ++i) {
			a.add(rL());
			sum = (sum + a.get(i)) % m;
			;
		}
		long ans = 0;

		for(int j=0;j<3;++j){
			Collections.shuffle(a);

			for (int i = 1; i <= (int) Math.pow(2, Math.min(18, n)); ++i) {
				long curAns = 0;
				for (int bit = 0; bit < Math.min(18, n); ++bit) {
					if (checkBit(i, bit) == 1) {
						curAns = (curAns + a.get(bit)) % m;
					}
				}
				ans = Math.max(curAns, ans);
			}
			Collections.shuffle(a);
			for (int i = 1; i <= (int) Math.pow(2, Math.min(18, n)); ++i) {
				long curAns = sum;
				for (int bit = 0; bit < Math.min(20, n); ++bit) {
					if (checkBit(i, bit) == 1) {
						curAns = (curAns - a.get(bit) % m + m) % m;
					}
				}
				ans = Math.max(curAns, ans);
			}
		}

		out.println(ans);
	}

	class SegmentTree {
		int[] t;

		SegmentTree(int[] a, int n) {
			t = new int[4 * n];
			build(a, 1, 1, n);
		}

		void build(int[] a, int v, int tl, int tr) {
			if (tl == tr) {
				t[v] = a[tl];
				return;
			}

			int tm = (tl + tr) / 2;
			build(a, 2 * v, tl, tm);
			build(a, 2 * v + 1, tm + 1, tr);
			t[v] = Math.min(t[2 * v], t[2 * v + 1]);
		}

		void update(int v, int tl, int tr, int pos, int value) {
			if (tl == tr) {
				t[v] = value;
				return;
			}
			int tm = (tl + tr) / 2;
			if (pos <= tm) {
				update(2 * v, tl, tm, pos, value);
			} else {
				update(2 * v + 1, tm + 1, tr, pos, value);
			}

			t[v] = Math.min(t[2 * v], t[2 * v + 1]);
		}

		int getMin(int v, int tl, int tr, int l, int r) {
			if (l > r) {
				return INF;
			}
			if (tl == l && tr == r) {
				return t[v];
			}

			int tm = (tl + tr) / 2;

			int min1 = getMin(2 * v, tl, tm, l, Math.min(tm, r));
			int min2 = getMin(2 * v + 1, tm + 1, tr, Math.max(l, tm + 1), r);

			return Math.min(min1, min2);
		}
	}

	int checkBit(int mask, int bit) {
		return (mask >> bit) & 1;
	}

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

		new Problem().run();
	}

	boolean isLower(char a) {
		return ((int) a) >= 97 ? true : false;
	}

	int INF = Integer.MAX_VALUE - 12345;

	int[][] STEPS = { { 0, 1 }, { 1, 0 }, { -1, 0 }, { 0, -1 } };

	BufferedReader in;
	PrintWriter out;
	StringTokenizer tok;
	Random rnd = new Random();
	static final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;

	Problem() throws FileNotFoundException {

		try {
			in = new BufferedReader(new FileReader("input.txt"));
			out = new PrintWriter("output.txt");
		} catch (Exception e) {
			in = new BufferedReader(new InputStreamReader(System.in));
			out = new PrintWriter(System.out);
		}

		tok = new StringTokenizer("");
	}

	long checkBit(long mask, int bit) {
		return (mask >> bit) & 1;
	}

	// ======================================================

	// ======================================================
	void run() throws IOException {
		solve();
		out.close();
	}

	char[] reverseCharArray(char[] arr) {
		char[] ans = new char[arr.length];
		for (int i = 0; i < arr.length; ++i) {
			ans[i] = arr[arr.length - i - 1];
		}
		return ans;
	}

	int sqrt(double m) {
		int l = 0;
		int r = 1000000000 + 9;
		int i = 1000;
		while (r - l > 1) {
			int mid = (r + l) / 2;
			if (mid * mid > m) {
				r = mid;
			} else {
				l = mid;
			}
		}
		return l;
	}

	int countPow(int m, int n) {
		int ans = 0;
		while (m % n == 0 && m > 0) {
			ans++;
			m /= n;
		}
		return ans;
	}

	long binPow(long a, long b) {
		if (b == 0) {
			return 1;
		}
		if (b % 2 == 1) {
			return a * binPow(a, b - 1);
		} else {
			long c = binPow(a, b / 2);
			return c * c;
		}

	}

	int gcd(int a, int b) {
		return b == 0 ? a : gcd(b, a % b);
	}

	long pow(long x, long k) {
		long ans = 1;
		for (int i = 0; i < k; ++i) {
			ans *= x;
		}
		return ans;
	}

	class Fenwik {
		private long[] t;
		private int length;

		Fenwik(int[] a) {
			this.length = a.length + 100;
			this.t = new long[length];
			for (int i = 0; i < a.length; ++i) {
				this.inc(i, a[i]);
			}
		}

		void inc(int i, int delta) {
			for (; i < this.length; i = i | (i + 1)) {
				this.t[i] += delta;
			}
		}

		long getSum(int r) {
			long sum = 0;

			for (; r >= 0; r = (r & (r + 1)) - 1) {
				sum += this.t[r];
			}

			return sum;
		}
	}

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

	String delimiter = " ";

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

	String rS() throws IOException {
		while (!tok.hasMoreTokens()) {
			String nextLine = readLine();
			if (null == nextLine)
				return null;

			tok = new StringTokenizer(nextLine);
		}

		return tok.nextToken(delimiter);
	}

	int rI() throws IOException {
		return Integer.parseInt(rS());
	}

	long rL() throws IOException {
		return Long.parseLong(rS());
	}

	double rD() throws IOException {
		return Double.parseDouble(rS());
	}

	int[] rA(int b) {
		int a[] = new int[b];
		for (int i = 0; i < b; i++) {
			try {
				a[i] = rI();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return a;
	}

	int[] readSortedIntArray(int size) throws IOException {
		Integer[] array = new Integer[size];

		for (int index = 0; index < size; ++index) {
			array[index] = rI();
		}
		Arrays.sort(array);

		int[] sortedArray = new int[size];
		for (int index = 0; index < size; ++index) {
			sortedArray[index] = array[index];
		}

		return sortedArray;
	}

	int[] sortedIntArray(int size, int[] array) throws IOException {
		for (int index = 0; index < size; ++index) {
			array[index] = rI();
		}
		Arrays.sort(array);

		int[] sortedArray = new int[size];
		for (int index = 0; index < size; ++index) {
			sortedArray[index] = array[index];
		}

		return sortedArray;
	}
}

import java.io.*;
import java.util.*;
import java.util.Map.Entry;
import java.lang.Math;
import java.math.BigInteger;

public class Problem {

	void solve() throws IOException {

		int n = rI();
		int m = rI();
		int[] a = rA(n);

		TreeSet<Integer> st1 = new TreeSet<>();
		TreeSet<Integer> st2 = new TreeSet<>();
		for (int mask = 0; mask < (int) Math.pow(2, Math.min(n / 2, 17)); ++mask) {
			int sum = 0;
			for (int bit = 0; bit < (int) Math.pow(2, Math.min(n / 2, 17)); ++bit) {
				if (checkBit(mask, bit) == 1) {
					sum = (sum + a[bit] % m) % m;
				}
			}
			st1.add(sum);
		}

		for (int mask = 0; mask < (int) Math.pow(2, Math.min(n / 2, 17)); ++mask) {
			int sum = 0;
			for (int bit = 0; bit < (int) Math.pow(2, Math.min(n / 2, 17)); ++bit) {
				if (checkBit(mask, bit) == 1) {
					sum = (sum + a[Math.min(n / 2, 17)+bit] % m) % m;
				}
			}
			st2.add(sum);
		}

		int ans = 0;
		for(int i: st1){
			if(st2.lower(m-i)!=null){
				ans = Math.max(ans, i+st2.lower(m-i));
			}
		}
		out.println(ans);
	}

	class SegmentTree {
		int[] t;

		SegmentTree(int[] a, int n) {
			t = new int[4 * n];
			build(a, 1, 1, n);
		}

		void build(int[] a, int v, int tl, int tr) {
			if (tl == tr) {
				t[v] = a[tl];
				return;
			}

			int tm = (tl + tr) / 2;
			build(a, 2 * v, tl, tm);
			build(a, 2 * v + 1, tm + 1, tr);
			t[v] = Math.min(t[2 * v], t[2 * v + 1]);
		}

		void update(int v, int tl, int tr, int pos, int value) {
			if (tl == tr) {
				t[v] = value;
				return;
			}
			int tm = (tl + tr) / 2;
			if (pos <= tm) {
				update(2 * v, tl, tm, pos, value);
			} else {
				update(2 * v + 1, tm + 1, tr, pos, value);
			}

			t[v] = Math.min(t[2 * v], t[2 * v + 1]);
		}

		int getMin(int v, int tl, int tr, int l, int r) {
			if (l > r) {
				return INF;
			}
			if (tl == l && tr == r) {
				return t[v];
			}

			int tm = (tl + tr) / 2;

			int min1 = getMin(2 * v, tl, tm, l, Math.min(tm, r));
			int min2 = getMin(2 * v + 1, tm + 1, tr, Math.max(l, tm + 1), r);

			return Math.min(min1, min2);
		}
	}

	int checkBit(int mask, int bit) {
		return (mask >> bit) & 1;
	}

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

		new Problem().run();
	}

	boolean isLower(char a) {
		return ((int) a) >= 97 ? true : false;
	}

	int INF = Integer.MAX_VALUE - 12345;

	int[][] STEPS = { { 0, 1 }, { 1, 0 }, { -1, 0 }, { 0, -1 } };

	BufferedReader in;
	PrintWriter out;
	StringTokenizer tok;
	Random rnd = new Random();
	static final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;

	Problem() throws FileNotFoundException {

		try {
			in = new BufferedReader(new FileReader("input.txt"));
			out = new PrintWriter("output.txt");
		} catch (Exception e) {
			in = new BufferedReader(new InputStreamReader(System.in));
			out = new PrintWriter(System.out);
		}

		tok = new StringTokenizer("");
	}

	long checkBit(long mask, int bit) {
		return (mask >> bit) & 1;
	}

	// ======================================================

	// ======================================================
	void run() throws IOException {
		solve();
		out.close();
	}

	char[] reverseCharArray(char[] arr) {
		char[] ans = new char[arr.length];
		for (int i = 0; i < arr.length; ++i) {
			ans[i] = arr[arr.length - i - 1];
		}
		return ans;
	}

	int sqrt(double m) {
		int l = 0;
		int r = 1000000000 + 9;
		int i = 1000;
		while (r - l > 1) {
			int mid = (r + l) / 2;
			if (mid * mid > m) {
				r = mid;
			} else {
				l = mid;
			}
		}
		return l;
	}

	int countPow(int m, int n) {
		int ans = 0;
		while (m % n == 0 && m > 0) {
			ans++;
			m /= n;
		}
		return ans;
	}

	long binPow(long a, long b) {
		if (b == 0) {
			return 1;
		}
		if (b % 2 == 1) {
			return a * binPow(a, b - 1);
		} else {
			long c = binPow(a, b / 2);
			return c * c;
		}

	}

	int gcd(int a, int b) {
		return b == 0 ? a : gcd(b, a % b);
	}

	long pow(long x, long k) {
		long ans = 1;
		for (int i = 0; i < k; ++i) {
			ans *= x;
		}
		return ans;
	}

	class Fenwik {
		private long[] t;
		private int length;

		Fenwik(int[] a) {
			this.length = a.length + 100;
			this.t = new long[length];
			for (int i = 0; i < a.length; ++i) {
				this.inc(i, a[i]);
			}
		}

		void inc(int i, int delta) {
			for (; i < this.length; i = i | (i + 1)) {
				this.t[i] += delta;
			}
		}

		long getSum(int r) {
			long sum = 0;

			for (; r >= 0; r = (r & (r + 1)) - 1) {
				sum += this.t[r];
			}

			return sum;
		}
	}

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

	String delimiter = " ";

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

	String rS() throws IOException {
		while (!tok.hasMoreTokens()) {
			String nextLine = readLine();
			if (null == nextLine)
				return null;

			tok = new StringTokenizer(nextLine);
		}

		return tok.nextToken(delimiter);
	}

	int rI() throws IOException {
		return Integer.parseInt(rS());
	}

	long rL() throws IOException {
		return Long.parseLong(rS());
	}

	double rD() throws IOException {
		return Double.parseDouble(rS());
	}

	int[] rA(int b) {
		int a[] = new int[b];
		for (int i = 0; i < b; i++) {
			try {
				a[i] = rI();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return a;
	}

	int[] readSortedIntArray(int size) throws IOException {
		Integer[] array = new Integer[size];

		for (int index = 0; index < size; ++index) {
			array[index] = rI();
		}
		Arrays.sort(array);

		int[] sortedArray = new int[size];
		for (int index = 0; index < size; ++index) {
			sortedArray[index] = array[index];
		}

		return sortedArray;
	}

	int[] sortedIntArray(int size, int[] array) throws IOException {
		for (int index = 0; index < size; ++index) {
			array[index] = rI();
		}
		Arrays.sort(array);

		int[] sortedArray = new int[size];
		for (int index = 0; index < size; ++index) {
			sortedArray[index] = array[index];
		}

		return sortedArray;
	}
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.List;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.TreeSet;
import java.io.InputStream;
import java.util.ArrayList;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author ankur
 */
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);
        ltimedec solver = new ltimedec();
        solver.solve(1, in, out);
        out.close();
    }

    static class ltimedec {
        long mod;
        int n;
        List<Long> li = new ArrayList<>();
        int[] ar;
        TreeSet<Long> li2 = new TreeSet<>();

        public void solve(int testNumber, InputReader in, PrintWriter out) {
            n = in.nextInt();
            mod = in.nextInt();
            ar = in.nextIntArray(n);
            subset(0, 0, n / 2);
            subset(n / 2, 0, n);
            long max = 0;
            //out.print();
            // System.out.println(li);
            for (int i = 0; i < li.size(); i++) {
                long val1 = mod - li.get(i) - 1;
                //System.out.println(val1);
                if (val1 <= li2.first()) {
                    long val2 = li2.floor(val1);
                    if (val2 != 1) {
                        max = Math.max(max, val1 + val2);
                    }
                }
                max = Math.max(max, li.get(i));
            }
            max = Math.max(max, li2.last());
            out.println(max);

        }

        void subset(int pos, long sum, int last) {
            if (pos == n) {
                li2.add(sum);
                return;
            }
            if (pos >= last) {
                li.add(sum);
                return;
            }
            subset(pos + 1, sum, last);
            subset(pos + 1, (sum + ar[pos]) % mod, last);

        }

    }

    static class InputReader {
        private final InputStream stream;
        private final byte[] buf = new byte[8192];
        private int curChar;
        private int snumChars;

        public InputReader(InputStream st) {
            this.stream = st;
        }

        public int read() {
            if (snumChars == -1)
                throw new InputMismatchException();
            if (curChar >= snumChars) {
                curChar = 0;
                try {
                    snumChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (snumChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }

        public int nextInt() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public int[] nextIntArray(int n) {
            int a[] = new int[n];
            for (int i = 0; i < n; i++) {
                a[i] = nextInt();
            }
            return a;
        }

        public boolean isSpaceChar(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

    }
}

import java.util.*;
import java.awt.List;
import java.io.*;
import java.lang.*;
import java.lang.reflect.Array;
public  class c2
{

	public static int mod = (int)Math.pow(10, 9) + 7;

    public static void main(String[] args)
    {
        InputReader in = new InputReader(System.in);
        PrintWriter pw = new PrintWriter(System.out);

        // Code starts..

        int n = in.nextInt();
        long m = in.nextLong();
        long[] a = new long[n];
        ArrayList<Long> l1 = new ArrayList<>();
        ArrayList<Long> l2 = new ArrayList<>();

        for(int i=0; i<n; i++)
        {
        	a[i] = in.nextLong()%m;
        	if(i<n/2)
        		l1.add(a[i]);
        	else
        		l2.add(a[i]);
        }

        TreeSet<Long> set2 = new TreeSet<>();
        TreeSet<Long> set1 = new TreeSet<>();

        fun(set1, 0, l1, 0, m);
        fun(set2, 0, l2, 0, m);

        long ans = 0;
        for(long p: set1)
        {

        	long p2 = m - p -1;
        	if(set2.floor(p2) != null )
        	{
        		p2 = set2.floor(p2);
        		ans = Math.max(ans, p + p2);
        	}

        }

        pw.println(ans);

        // code ends...

        pw.flush();
        pw.close();
    }

    public static void fun(TreeSet<Long> set, int idx, ArrayList<Long> list, long sum, long m) {

    	if(idx==list.size())
    		return;
    	set.add((sum + list.get(idx))%m);
    	fun(set, idx+1, list, sum, m);
    	fun(set, idx+1, list, (sum+list.get(idx))%m, m);

    }

    public static void factSieve(int[] fact, long n)
    {

        for (int i = 2; i <= n; i += 2)
            fact[i] = 2;

        for (int i = 3; i <= n; i += 2) {
            if (fact[i] == 0) {
                fact[i] = i;

                for (int j = i; (long) j * i <= n; j++) {
                    fact[(int) ((long) i * j)] = i;
                }
            }
        }

        /*
         * int k = 1000; while(k!=1) { System.out.print(a[k]+" "); k /= a[k];
         *
         * }
         */
    }

    public static int gcd(int p2, int p22)
    {
        if (p2 == 0)
            return (int) p22;
        return gcd(p22 % p2, p2);
    }

    public static void nextGreater(long[] a, int[] ans)
    {

        Stack<Integer> stk = new Stack<>();
        stk.push(0);

        for (int i = 1; i < a.length; i++) {

            if (!stk.isEmpty()) {
                int s = stk.pop();
                while (a[s] < a[i]) {
                    ans[s] = i;
                    if (!stk.isEmpty())
                        s = stk.pop();
                    else
                        break;
                }
                if (a[s] >= a[i])
                    stk.push(s);
            }

            stk.push(i);

        }
        return;

    }

    public static void nextGreaterRev(long[] a, int[] ans)
    {

        int n = a.length;
        int[] pans = new int[n];
        Arrays.fill(pans, -1);
        long[] arev = new long[n];
        for (int i = 0; i < n; i++)
            arev[i] = a[n - 1 - i];

        Stack<Integer> stk = new Stack<>();
        stk.push(0);

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

            if (!stk.isEmpty()) {
                int s = stk.pop();
                while (arev[s] < arev[i]) {
                    pans[s] = n - i - 1;
                    if (!stk.isEmpty())
                        s = stk.pop();
                    else
                        break;
                }
                if (arev[s] >= arev[i])
                    stk.push(s);
            }

            stk.push(i);

        }

        // for(int i=0; i<n; i++)
        // System.out.print(pans[i]+" ");

        for (int i = 0; i < n; i++)
            ans[i] = pans[n - i - 1];

        return;

    }

    public static void nextSmaller(long[] a, int[] ans)
    {

        Stack<Integer> stk = new Stack<>();
        stk.push(0);

        for (int i = 1; i < a.length; i++) {

            if (!stk.isEmpty()) {
                int s = stk.pop();
                while (a[s] > a[i]) {
                    ans[s] = i;
                    if (!stk.isEmpty())
                        s = stk.pop();
                    else
                        break;
                }
                if (a[s] <= a[i])
                    stk.push(s);
            }

            stk.push(i);

        }
        return;

    }

    public static long lcm(int[] numbers)
    {
        long lcm = 1;
        int divisor = 2;
        while (true) {
            int cnt = 0;
            boolean divisible = false;
            for (int i = 0; i < numbers.length; i++) {
                if (numbers[i] == 0) {
                    return 0;
                } else if (numbers[i] < 0) {
                    numbers[i] = numbers[i] * (-1);
                }
                if (numbers[i] == 1) {
                    cnt++;
                }
                if (numbers[i] % divisor == 0) {
                    divisible = true;
                    numbers[i] = numbers[i] / divisor;
                }
            }
            if (divisible) {
                lcm = lcm * divisor;
            } else {
                divisor++;
            }
            if (cnt == numbers.length) {
                return lcm;
            }
        }
    }

    public static long fact(long n)
    {

        long factorial = 1;
        for (int i = 1; i <= n; i++) {
            factorial *= i;
        }
        return factorial;
    }

    public static long choose(long total, long choose)
    {
        if (total < choose)
            return 0;
        if (choose == 0 || choose == total)
            return 1;
        return (choose(total - 1, choose - 1) + choose(total - 1, choose)) % mod;
    }

    public static int[] suffle(int[] a, Random gen)
    {
        int n = a.length;
        for (int i = 0; i < n; i++) {
            int ind = gen.nextInt(n - i) + i;
            int temp = a[ind];
            a[ind] = a[i];
            a[i] = temp;
        }
        return a;
    }

    public static int[] sufflesort(int[] a)
    {
        int n = a.length;
        Random gen = new Random();
        for (int i = 0; i < n; i++) {
            int ind = gen.nextInt(n - i) + i;
            int temp = a[ind];
            a[ind] = a[i];
            a[i] = temp;
        }
        Arrays.sort(a);
        return a;
    }

    public static int floorSearch(int arr[], int low, int high, int x)
    {
        if (low > high)
            return -1;

        if (x > arr[high])
            return high;
        int mid = (low + high) / 2;

        if (mid > 0 && arr[mid - 1] < x && x < arr[mid])
            return mid - 1;

        if (x < arr[mid])
            return floorSearch(arr, low, mid - 1, x);

        return floorSearch(arr, mid + 1, high, x);
    }

    public static void swap(int a, int b) {
        int temp = a;
        a = b;
        b = temp;
    }

    public static ArrayList<Integer> primeFactorization(int n)
    {
        ArrayList<Integer> a = new ArrayList<Integer>();
        for (int i = 2; i * i <= n; i++) {
            while (n % i == 0) {
                a.add(i);
                n /= i;
            }
        }
        if (n != 1)
            a.add(n);
        return a;
    }

    public static void sieve(boolean[] isPrime, int n)
    {
        for (int i = 1; i < n; i++)
            isPrime[i] = true;

        isPrime[0] = false;
        isPrime[1] = false;

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

    public static int lowerbound(ArrayList<Long> net, long c2)
    {
        int i = Collections.binarySearch(net, c2);
        if (i < 0)
            i = -(i + 2);
        return i;

    }

    public static int lowerboundArray(int[] dis, int c2)
    {
        int i = Arrays.binarySearch(dis, c2);

        if (i < 0)
            i = -(i + 2);
        return i;

    }

    public static int uperbound(ArrayList<Integer> list, int c2)
    {
        int i = Collections.binarySearch(list, c2);
        if (i < 0)
            i = -(i + 1);
        return i;

    }

    public static int uperboundArray(int[] dis, int c2)
    {
        int i = Arrays.binarySearch(dis, c2);
        if (i < 0)
            i = -(i + 1);
        return i;

    }

    public static int GCD(int a, int b)
    {
        if (b == 0)
            return a;
        else
            return GCD(b, a % b);
    }

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

    public static int d1;
    public static int p1;
    public static int q1;

    public static void extendedEuclid(int A, int B)
    {
        if (B == 0) {
            d1 = A;
            p1 = 1;
            q1 = 0;
        } else {
            extendedEuclid(B, A % B);
            int temp = p1;
            p1 = q1;
            q1 = temp - (A / B) * q1;
        }
    }

    public static long LCM(long a, long b) {
        return (a * b) / GCD(a, b);
    }

    public static int LCM(int a, int b) {
        return (a * b) / GCD(a, b);
    }

    public static int binaryExponentiation(int x, int n) {
        int result = 1;
        while (n > 0) {
            if (n % 2 == 1)
                result = result * x;
            x = x * x;
            n = n / 2;
        }
        return result;
    }

    public static int[] countDer(int n) {
        int der[] = new int[n + 1];

        der[0] = 1;
        der[1] = 0;
        der[2] = 1;

        for (int i = 3; i <= n; ++i)
            der[i] = (i - 1) * (der[i - 1] + der[i - 2]);

        // Return result for n
        return der;
    }

    static long binomialCoeff(int n, int k) {
        long C[][] = new long[n + 1][k + 1];
        int i, j;

        // Calculate value of Binomial Coefficient in bottom up manner
        for (i = 0; i <= n; i++) {
            for (j = 0; j <= Math.min(i, k); j++) {
                // Base Cases
                if (j == 0 || j == i)
                    C[i][j] = 1;

                // Calculate value using previosly stored values
                else
                    C[i][j] = C[i - 1][j - 1] + C[i - 1][j];
            }
        }

        return C[n][k];
    }

    public static long binaryExponentiation(long x, long n) {
        long result = 1;
        while (n > 0) {
            if (n % 2 == 1)
                result = result * x;
            x = (x % mod * x % mod) % mod;
            n = n / 2;
        }
        return result;
    }

    public static int modularExponentiation(int x, int n, int M) {
        int result = 1;
        while (n > 0) {
            if (n % 2 == 1)
                result = (result * x) % M;
            x = (x * x) % M;
            n = n / 2;
        }
        return result;
    }

    public static long modularExponentiation(long x, long n, long M) {
        long result = 1;
        while (n > 0) {
            if (n % 2 == 1)
                result = (result * x) % M;
            x = (x * x) % M;
            n = n / 2;
        }
        return result;
    }

    public static int modInverse(int A, int M) {
        return modularExponentiation(A, M - 2, M);
    }

    public static long sie(long A, long M) {
        return modularExponentiation(A, M - 2, M);
    }

    public static boolean isPrime(int n) {

        if (n <= 1)
            return false;
        if (n <= 3)
            return true;

        if (n % 2 == 0 || n % 3 == 0)
            return false;

        for (int i = 5; i * i <= n; i = i + 6) {
            if (n % i == 0 || n % (i + 2) == 0)
                return false;
        }

        return true;
    }

    static class pair implements Comparable<pair>

    {
        Integer x, y;

        pair(int x, int y) {
            this.x = x;
            this.y = y;
        }

        public int compareTo(pair o) {
            int result = x.compareTo(o.x);
            if (result == 0)
                result = y.compareTo(o.y);

            return result;
        }

        public String toString() {
            return x + " " + y;
        }

        public boolean equals(Object o) {
            if (o instanceof pair) {
                pair p = (pair) o;
                return p.x == x && p.y == y;
            }
            return false;
        }

        public int hashCode() {
            return new Long(x).hashCode() * 31 + new Long(y).hashCode();
        }

    }

    static class triplet implements Comparable<triplet> {
        Integer x, y, z;

        triplet(int x, int y, int z) {
            this.x = x;
            this.y = y;
            this.z = z;
        }

        public int compareTo(triplet o) {
            int result = x.compareTo(o.x);
            if (result == 0)
                result = y.compareTo(o.y);
            if (result == 0)
                result = z.compareTo(o.z);

            return result;
        }

        public boolean equlas(Object o) {
            if (o instanceof triplet) {
                triplet p = (triplet) o;
                return x == p.x && y == p.y && z == p.z;
            }
            return false;
        }

        public String toString() {
            return x + " " + y + " " + z;
        }

        public int hashCode() {
            return new Long(x).hashCode() * 31 + new Long(y).hashCode() + new Long(z).hashCode();
        }
    }

    /*
     * static class node implements Comparable<node>
     *
     * { Integer x, y, z; node(int x,int y, int z) { this.x=x; this.y=y; this.z=z; }
     *
     * public int compareTo(pair o) { int result = x.compareTo(o.x); if(result==0)
     * result = y.compareTo(o.y); if(result==0) result = z.compareTo(z); return
     * result; }
     *
     * @Override public int compareTo(node o) { // TODO Auto-generated method stub
     * return 0; } }
     */

    static class InputReader
	{

		private final InputStream stream;
		private final byte[] buf = new byte[8192];
		private int curChar, snumChars;
		private SpaceCharFilter filter;

		public InputReader(InputStream stream)
		{
			this.stream = stream;
		}

		public int snext()
		{
			if (snumChars == -1)
				throw new InputMismatchException();
			if (curChar >= snumChars)
			{
				curChar = 0;
				try
				{
					snumChars = stream.read(buf);
				}
				catch (IOException e)
				{
					throw new InputMismatchException();
				}
				if (snumChars <= 0)
					return -1;
			}
			return buf[curChar++];
		}

		public int nextInt()
	    {
			int c = snext();
			while (isSpaceChar(c))
			{
				c = snext();
			}
			int sgn = 1;
			if (c == '-')
		    {
				sgn = -1;
				c = snext();
			}
			int res = 0;
			do
			{
				if (c < '0' || c > '9')
					throw new InputMismatchException();
				res *= 10;
				res += c - '0';
				c = snext();
			} while (!isSpaceChar(c));
			return res * sgn;
		}

		public long nextLong()
	    {
			int c = snext();
			while (isSpaceChar(c))
			{
				c = snext();
			}
			int sgn = 1;
			if (c == '-')
			{
				sgn = -1;
				c = snext();
			}
			long res = 0;
			do
			{
				if (c < '0' || c > '9')
					throw new InputMismatchException();
				res *= 10;
				res += c - '0';
				c = snext();
			} while (!isSpaceChar(c));
			return res * sgn;
		}

		public int[] nextIntArray(int n)
		{
			int a[] = new int[n];
			for (int i = 0; i < n; i++)
			{
				a[i] = nextInt();
			}
			return a;
		}

		public String readString()
	    {
			int c = snext();
			while (isSpaceChar(c))
			{
				c = snext();
			}
			StringBuilder res = new StringBuilder();
			do
			{
				res.appendCodePoint(c);
				c = snext();
			} while (!isSpaceChar(c));
			return res.toString();
		}

		public String nextLine()
		{
			int c = snext();
			while (isSpaceChar(c))
				c = snext();
			StringBuilder res = new StringBuilder();
			do
			{
				res.appendCodePoint(c);
				c = snext();
			} while (!isEndOfLine(c));
			return res.toString();
		}

		public boolean isSpaceChar(int c)
		{
			if (filter != null)
				return filter.isSpaceChar(c);
			return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
		}

		private boolean isEndOfLine(int c)
		{
			return c == '\n' || c == '\r' || c == -1;
		}

		public interface SpaceCharFilter
	    {
			public boolean isSpaceChar(int ch);
		}
	}

}

import java.util.HashSet;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;

public class MaxSubSeq {
public static void main(String[] args) {
	Scanner s = new Scanner(System.in);
	int n = s.nextInt();
	int m = s.nextInt();
	int x = 0;
	if(n%2!=0) {
		x=1;
	}
	int[] a = new int[n/2];
	int[] b = new int[n/2+x];
	for (int i = 0; i < a.length; i++) {
		a[i] = s.nextInt();
	}
	for (int i = 0; i < b.length; i++) {
		b[i] = s.nextInt();
	}
	s.close();
	TreeSet<Integer> posA = getSums(a,m);
	TreeSet<Integer> posB = getSums(a,m);
	Iterator<Integer> it = posA.iterator();
	Iterator<Integer> bit = posB.descendingIterator();
	int max = 0;
	int bEl = bit.next();
	while(it.hasNext()) {
		int aEl = it.next();
		while(aEl+bEl>m) {
			bEl = bit.next();
		}
		max = Math.max((aEl+bEl)%m, max);
	}
	System.out.println(max);

}

private static TreeSet<Integer> getSums(int[] a, int m) {
	TreeSet<Integer> obtained = new TreeSet<>();
	obtained.add(0);
	for (int i = 0; i<a.length; i++) {
		Integer[] copy = obtained.toArray(new Integer[0]);
		for(int j:copy) {
			obtained.add((j+a[i])%m);
		}
	}
	return obtained;
}
}

//package Round888;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Scanner;
import java.util.TreeSet;

public class E_MeetInTheMiddle {
    private static int n, m;
    private static Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        n = scanner.nextInt();
        m = scanner.nextInt();

        TreeSet<Integer> set1 = create_set(n / 2);
        TreeSet<Integer> set2 = create_set(n - n / 2);

        Iterator<Integer> iter2 = set2.iterator();

        int max_value = Integer.MIN_VALUE;
        while (iter2.hasNext()) {
            int v2 = iter2.next();
            Integer v1 = set1.floor(m - 1 - v2);
            if (v1 != null)
                max_value = max(max_value, v2 + v1);
        }

        System.out.println(max_value);
    }

    private static TreeSet<Integer> create_set(int count) {
        TreeSet<Integer> set = new TreeSet<>();

        for (int i = 0; i < count; i++) {
            int e = scanner.nextInt() % m;

            Iterator<Integer> iterator = set.iterator();
            ArrayList<Integer> arrayList = new ArrayList<>(set.size() + 1);

            while (iterator.hasNext()) {
                int t = (iterator.next() + e) % m;
                arrayList.add(t);
            }

            arrayList.add(e);
            set.addAll(arrayList);
        }

        set.add(0);
        if (set.contains(n - 1)) {
            System.out.println(n - 1);
            System.exit(0);
        }

        return set;
    }

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

//package Round;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Scanner;

public class E {
    private static int n;

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        n = scanner.nextInt();
        int m = scanner.nextInt();

        HashSet<Integer> set = new HashSet<>((int) (n / 0.75 + 2));
        int max_value = Integer.MIN_VALUE;

        for (int i = 0; i < n; i++) {
            int e = scanner.nextInt() % m;
            if (e == n - 1) out();

            Iterator<Integer> iterator = set.iterator();
            ArrayList<Integer> arrayList = new ArrayList<>(set.size());

            while (iterator.hasNext()) {
                int t = (iterator.next() + e) % m;
                if (t == n - 1) out();
                arrayList.add(t);
                max_value = max(max_value, t);
            }

            arrayList.add(e);
            max_value = max(max_value, e);
            set.addAll(arrayList);
        }

        System.out.println(max_value);
    }

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

    private static void out() {
        System.out.println(n - 1);
        System.exit(0);
    }
}

/**
 * Date: 28 Sep, 2019
 * Link:
 *
 * @author Prasad Chaudhari
 * @linkedIn: https://www.linkedin.com/in/prasad-chaudhari-841655a6/
 * @git: https://github.com/Prasad-Chaudhari
 */
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.util.TreeSet;

public class newProgram0 {

    public static void main(String[] args) throws IOException {
        // TODO code application logic here
        FastIO in = new FastIO();
        int n = in.ni();
        int mod = in.ni();
        int a[] = in.gia(n);
        TreeSet<Long> s1 = new TreeSet<>();
        for (int i = 0; i < Math.pow(2, n / 2); i++) {
            long sum = 0;
            int temp = i;
            for (int j = 0; j < n / 2; j++) {
                if (temp % 2 == 1) {
                    sum += a[j];
                }
            }
            s1.add(sum % mod);
        }
        TreeSet<Long> s2 = new TreeSet<>();
        for (int i = 0; i < Math.pow(2, n - (n / 2)); i++) {
            long sum = 0;
            int temp = i;
            for (int j = n / 2; j < n; j++) {
                if (temp % 2 == 1) {
                    sum += a[j];
                }
            }
            s2.add(sum % mod);
        }
        long max = 0;
        for (long i : s1) {
            Long ans = s2.floor(mod - 1l - i);
            if (ans != null) {
                max = Math.max(max, i + ans);
            }
        }
        System.out.println(max);
        in.bw.flush();
    }

    static class Data implements Comparable<Data> {

        int a, b;

        public Data(int a, int b) {
            this.a = a;
            this.b = b;
        }

        @Override
        public int compareTo(Data o) {
            if (a == o.a) {
                return Integer.compare(b, o.b);
            }
            return Integer.compare(a, o.a);
        }

        public static void sort(int a[]) {
            Data d[] = new Data[a.length];
            for (int i = 0; i < a.length; i++) {
                d[i] = new Data(a[i], 0);
            }
            Arrays.sort(d);
            for (int i = 0; i < a.length; i++) {
                a[i] = d[i].a;
            }
        }
    }

    static class FastIO {

        private final BufferedReader br;
        private final BufferedWriter bw;
        private String s[];
        private int index;

        public FastIO() throws IOException {
            br = new BufferedReader(new InputStreamReader(System.in));
            bw = new BufferedWriter(new OutputStreamWriter(System.out, "UTF-8"));
            s = br.readLine().split(" ");
            index = 0;
        }

        public int ni() throws IOException {
            return Integer.parseInt(nextToken());
        }

        public double nd() throws IOException {
            return Double.parseDouble(nextToken());
        }

        public long nl() throws IOException {
            return Long.parseLong(nextToken());
        }

        public String next() throws IOException {
            return nextToken();
        }

        public String nli() throws IOException {
            try {
                return br.readLine();
            } catch (IOException ex) {

            }
            return null;
        }

        public int[] gia(int n) throws IOException {
            int a[] = new int[n];
            for (int i = 0; i < n; i++) {
                a[i] = ni();
            }
            return a;
        }

        public int[] gia(int n, int start, int end) throws IOException {
            validate(n, start, end);
            int a[] = new int[n];
            for (int i = start; i < end; i++) {
                a[i] = ni();
            }
            return a;
        }

        public double[] gda(int n) throws IOException {
            double a[] = new double[n];
            for (int i = 0; i < n; i++) {
                a[i] = nd();
            }
            return a;
        }

        public double[] gda(int n, int start, int end) throws IOException {
            validate(n, start, end);
            double a[] = new double[n];
            for (int i = start; i < end; i++) {
                a[i] = nd();
            }
            return a;
        }

        public long[] gla(int n) throws IOException {
            long a[] = new long[n];
            for (int i = 0; i < n; i++) {
                a[i] = nl();
            }
            return a;
        }

        public long[] gla(int n, int start, int end) throws IOException {
            validate(n, start, end);
            long a[] = new long[n];
            for (int i = start; i < end; i++) {
                a[i] = nl();
            }
            return a;
        }

        public int[][][] gwtree(int n) throws IOException {
            int m = n - 1;
            int adja[][] = new int[n + 1][];
            int weight[][] = new int[n + 1][];
            int from[] = new int[m];
            int to[] = new int[m];
            int count[] = new int[n + 1];
            int cost[] = new int[n + 1];
            for (int i = 0; i < m; i++) {
                from[i] = i + 1;
                to[i] = ni();
                cost[i] = ni();
                count[from[i]]++;
                count[to[i]]++;
            }
            for (int i = 0; i <= n; i++) {
                adja[i] = new int[count[i]];
                weight[i] = new int[count[i]];
            }
            for (int i = 0; i < m; i++) {
                adja[from[i]][count[from[i]] - 1] = to[i];
                adja[to[i]][count[to[i]] - 1] = from[i];
                weight[from[i]][count[from[i]] - 1] = cost[i];
                weight[to[i]][count[to[i]] - 1] = cost[i];
                count[from[i]]--;
                count[to[i]]--;
            }
            return new int[][][] { adja, weight };
        }

        public int[][][] gwg(int n, int m) throws IOException {
            int adja[][] = new int[n + 1][];
            int weight[][] = new int[n + 1][];
            int from[] = new int[m];
            int to[] = new int[m];
            int count[] = new int[n + 1];
            int cost[] = new int[n + 1];
            for (int i = 0; i < m; i++) {
                from[i] = ni();
                to[i] = ni();
                cost[i] = ni();
                count[from[i]]++;
                count[to[i]]++;
            }
            for (int i = 0; i <= n; i++) {
                adja[i] = new int[count[i]];
                weight[i] = new int[count[i]];
            }
            for (int i = 0; i < m; i++) {
                adja[from[i]][count[from[i]] - 1] = to[i];
                adja[to[i]][count[to[i]] - 1] = from[i];
                weight[from[i]][count[from[i]] - 1] = cost[i];
                weight[to[i]][count[to[i]] - 1] = cost[i];
                count[from[i]]--;
                count[to[i]]--;
            }
            return new int[][][] { adja, weight };
        }

        public int[][] gtree(int n) throws IOException {
            int adja[][] = new int[n + 1][];
            int from[] = new int[n - 1];
            int to[] = new int[n - 1];
            int count[] = new int[n + 1];
            for (int i = 0; i < n - 1; i++) {
                from[i] = i + 1;
                to[i] = ni();
                count[from[i]]++;
                count[to[i]]++;
            }
            for (int i = 0; i <= n; i++) {
                adja[i] = new int[count[i]];
            }
            for (int i = 0; i < n - 1; i++) {
                adja[from[i]][--count[from[i]]] = to[i];
                adja[to[i]][--count[to[i]]] = from[i];
            }
            return adja;
        }

        public int[][] gg(int n, int m) throws IOException {
            int adja[][] = new int[n + 1][];
            int from[] = new int[m];
            int to[] = new int[m];
            int count[] = new int[n + 1];
            for (int i = 0; i < m; i++) {
                from[i] = ni();
                to[i] = ni();
                count[from[i]]++;
                count[to[i]]++;
            }
            for (int i = 0; i <= n; i++) {
                adja[i] = new int[count[i]];
            }
            for (int i = 0; i < m; i++) {
                adja[from[i]][--count[from[i]]] = to[i];
                adja[to[i]][--count[to[i]]] = from[i];
            }
            return adja;
        }

        public void print(String s) throws IOException {
            bw.write(s);
        }

        public void println(String s) throws IOException {
            bw.write(s);
            bw.newLine();
        }

        public void print(int s) throws IOException {
            bw.write(s + "");
        }

        public void println(int s) throws IOException {
            bw.write(s + "");
            bw.newLine();
        }

        public void print(long s) throws IOException {
            bw.write(s + "");
        }

        public void println(long s) throws IOException {
            bw.write(s + "");
            bw.newLine();
        }

        public void print(double s) throws IOException {
            bw.write(s + "");
        }

        public void println(double s) throws IOException {
            bw.write(s + "");
            bw.newLine();
        }

        private String nextToken() throws IndexOutOfBoundsException, IOException {
            if (index == s.length) {
                s = br.readLine().split(" ");
                index = 0;
            }
            return s[index++];
        }

        private void validate(int n, int start, int end) {
            if (start < 0 || end >= n) {
                throw new IllegalArgumentException();
            }
        }
    }
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.util.TreeSet;

public class CF0888E_MaximumSubsequence {
	static class Scanner {
		BufferedReader br;
		StringTokenizer st;

		public Scanner() {
			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 void print(Object b) {
		System.out.print(b);
	}

	static void println(Object b) {
		System.out.println(b);
	}

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

	static int[] arr1;
	static int[] arr2;
	static TreeSet<Integer> set;
	static ArrayList<Integer> arr;
	static int m;

	static void dfs1(int i, int sum) {
		if (i == arr1.length) {
			set.add(sum);
			return;
		}
		dfs1(i + 1, sum);
		dfs1(i + 1, (sum + arr1[i]) % m);
	}

	static void dfs2(int i, int sum) {
		if (i == arr2.length) {
			arr.add(sum);
			return;
		}
		dfs2(i + 1, sum);
		dfs2(i + 1, (sum + arr2[i]) % m);
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner scanner = new Scanner();
		int n = scanner.nextInt();
		m = scanner.nextInt();
		int two = n / 2;
		if (n % 2 == 1)
			two++;
		arr1 = new int[n / 2];
		arr2 = new int[two];
		for (int i = 0; i < arr1.length; i++)
			arr1[i] = scanner.nextInt();
		for (int i = 0; i < arr2.length; i++)
			arr2[i] = scanner.nextInt();
		set = new TreeSet<Integer>();
		arr = new ArrayList<Integer>();
		dfs1(0, 0);
		dfs2(0, 0);

		int ans = 0;
		for (int i = 0; i < arr.size(); i++) {
			if(arr.get(i) %m == 0)
				continue;
			ans = Math.max(ans, (set.lower(m - arr.get(i)) + arr.get(i)) % m);
			ans = Math.max(ans, (set.lower(2 * m - arr.get(i)) + arr.get(i)) % m);
		}
		println(ans);
	}

}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.util.TreeSet;

public class CF0888E_MaximumSubsequence {
	static class Scanner {
		BufferedReader br;
		StringTokenizer st;

		public Scanner() {
			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 void print(Object b) {
		System.out.print(b);
	}

	static void println(Object b) {
		System.out.println(b);
	}

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

	static int[] arr1;
	static int[] arr2;
	static TreeSet<Integer> set;
	static ArrayList<Integer> arr;
	static int m;

	static void dfs1(int i, int sum) {
		if (i == arr1.length) {
			set.add(sum);
			return;
		}
		dfs1(i + 1, sum);
		dfs1(i + 1, (sum + arr1[i]) % m);
	}

	static void dfs2(int i, int sum) {
		if (i == arr2.length) {
			arr.add(sum);
			return;
		}
		dfs2(i + 1, sum);
		dfs2(i + 1, (sum + arr2[i]) % m);
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner scanner = new Scanner();
		int n = scanner.nextInt();
		m = scanner.nextInt();
		int two = n / 2;
		if (n % 2 == 1)
			two++;
		arr1 = new int[n / 2];
		arr2 = new int[two];
		for (int i = 0; i < arr1.length; i++)
			arr1[i] = scanner.nextInt();
		for (int i = 0; i < arr2.length; i++)
			arr2[i] = scanner.nextInt();
		set = new TreeSet<Integer>();
		arr = new ArrayList<Integer>();
		dfs1(0, 0);
		dfs2(0, 0);

		int ans = 0;
		for (int i = 0; i < arr.size(); i++) {
			ans = Math.max(ans, (set.floor(m - arr.get(i)) + arr.get(i)) % m);
			ans = Math.max(ans, (set.floor(2 * m - arr.get(i)) + arr.get(i)) % m);
		}
		println(ans);
	}

}

import java.io.PrintWriter;
import java.util.Scanner;

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

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

        for (int i = 1; i < n + 1; i++) {
            a[i] = in.nextInt();
        }

        long[] dp = new long[n + 1];
        dp[0] = 0;
        for (int i = 1; i < n + 1; i++) {
            dp[i] = Math.max(dp[i - 1], (dp[i - 1] + a[i]) % m);
        }

        out.println(dp[n]);

        in.close();
        out.close();
    }
}

import java.io.PrintWriter;
import java.util.Scanner;

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

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

        for (int i = 1; i < n + 1; i++) {
            a[i] = in.nextInt();
        }

        int[] dp = new int[n + 1];
        dp[0] = 0;
        for (int i = 1; i < n + 1; i++) {
            dp[i] = Math.max(dp[i - 1], (dp[i - 1] + a[i]) % m);
        }

        out.println(dp[n]);

        in.close();
        out.close();
    }
}

import java.io.PrintWriter;
import java.util.Scanner;

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

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

        for (int i = 1; i < n + 1; i++) {
            a[i] = in.nextInt();
        }

        long[] dp = new long[n + 1];
        dp[0] = 0;
        for (int i = 1; i < n + 1; i++) {
            dp[i] = Math.max(dp[i - 1], (dp[i - 1] + a[i]) % m);
        }

        out.println(dp[n]);

        in.close();
        out.close();
    }
}

import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;

public class Main {

	public static ArrayList<Integer>g1 = new ArrayList<>();

	public static int bSearch(int val){
		int st = 0, end = g1.size() - 1;

		while(st < end){
			int mid = st + (end - st + 1) / 2;

			if(g1.get(mid) < val){
				st = mid;

			}else{

				end = mid - 1;
			}
		}
		return g1.get(st);
	}

	public static void main(String [] args){
		Scanner scanner = new Scanner(System.in);
		int n = scanner.nextInt();
		int m = scanner.nextInt();
		int size1 = n/2;
		ArrayList<Integer>nums = new ArrayList<>();

		for(int i = 0; i < n; i++){
			nums.add(scanner.nextInt());
		}

		for(int msk = 0; msk < (1 << size1); msk++){

			int sum = 0;
			for(int i = 0; i < size1; i++){
				if((msk & (1 << i)) >= 1){
					sum+= nums.get(i);
					sum%= m;
				}
			}

			g1.add(sum);
		}
		Collections.sort(g1);

		int res = 0;
		for(int msk = 0; msk < (1 << n - size1); msk++){

			int sum = 0;
			for(int i = 0; i < n - size1; i++){
				if((msk & (1 << i)) == 1){
					sum+= nums.get(size1 + i);
					sum%= m;
				}
			}

			int val = m - sum;
			res =  Math.max(res, sum + bSearch(val));
		}

		System.out.println(res);
	}
}

import java.io.*; import java.util.*;
public class CF888E {

    /**
     * Idea: split the sequence into two parts of size <=18
     *
     * Perform a bitmasking search for the two parts
     * Sort two parts
     * And merge
     *
     * To merge, we first consider the sum of largest elements.
     *
     * Now perform a two pointer on sum <=MOD to get largest sum <=MOD
     * DONE
     */
    public static void main(String[] args) throws IOException {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st=new StringTokenizer(br.readLine());
        int N=Integer.parseInt(st.nextToken());
        int MOD=Integer.parseInt(st.nextToken());
        st=new StringTokenizer(br.readLine());
        int[] p1=new int[N/2];
        for (int i = 0; i < N/2; i++) {
            p1[i]=Integer.parseInt(st.nextToken())%MOD;
        }
        int[] p2=new int[N-N/2];
        for (int i = 0; i < N-N/2; i++) {
            p2[i]=Integer.parseInt(st.nextToken())%MOD;
        }

        ArrayList<Integer> res1=new ArrayList<>();
        int cur=0;
        for (int i = 0; i < (1<<N/2); i++) {
            cur=0;
            for (int j = 0; j < N/2; j++) {
                if((i&(1<<j))>0){
                    cur+=p1[j]; cur%=MOD;
                }
            }
            res1.add(cur);
        }
        ArrayList<Integer> res2=new ArrayList<>();
        for (int i = 0; i < (1<<(N-N/2)); i++) {
            cur=0;
            for (int j = 0; j < N/2; j++) {
                if((i&(1<<j))>0){
                    cur+=p2[j]; cur%=MOD;
                }
            }
            res2.add(cur);
        }
        Collections.sort(res1); Collections.sort(res2);

        int max=(res1.get(res1.size()-1)+res2.get(res2.size()-1))%MOD;
        //Now consider sums <MOD, we use 2 pointers
        int rp=res2.size()-1;
        for (int l = 0; l < res1.size(); l++) {
            while(rp>=0 && res1.get(l)+res2.get(rp)>=MOD){
                rp--;
            }
            if(rp<0){
                break;
            }
            max=Math.max(max,res1.get(l)+res2.get(rp));
        }
        System.out.println(max);
    }

}

//package sept;

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

public class TimePass {
    InputStream is;
    PrintWriter out;
    String INPUT = "";
    //boolean codechef=true;
    boolean codechef=true;

	void solve()
	{
		int n=ni(),m=ni();
		int[] a=na(n);
		HashMap<Integer,Integer> map=new HashMap<>();
		int sum=0;
		for(int i=0;i<n;i++)
		{
			a[i]%=m;
			if(map.containsKey(a[i]))
			{
				map.put(a[i],map.get(a[i])+1);
			}
			else map.put(a[i], 1);
			sum+=a[i];
			sum%=m;
		}
		if(map.containsKey(m-1))
		{
			out.println(m-1);
			return;
		}
		int max=0;
		for(int i=0;i<Math.pow(2, n/2+1);i++)
		{
			int curr=i,s=0;
			while(curr!=0)
			{
				if(curr%2==1)s+=curr;
				s%=m;
				curr/=2;
			}
			max=Math.max(max, s);
			max=Math.max(max, (sum-s+m)%m);
		}
		out.println(max);
	}

	static int[][] packD(int n,int[] from,int[] to)
	{
		int[][] g=new int[n][];
		int[] p=new int[n];
		for(int f:from)
		{
			p[f]++;
		}
		int m=from.length;
		for(int i=0;i<n;i++)
		{
			g[i]=new int[p[i]];
		}
		for(int i=0;i<m;i++)
		{
			g[from[i]][--p[from[i]]]=to[i];
		}
		return g;
	}

    static class Pair
    {
        int a,b;
        public Pair(int a,int b)
        {
            this.a=a;
            this.b=b;
        }
    }

    static long lcm(int a,int b)
    {
        long val=a;
        val*=b;
        return (val/gcd(a,b));
    }

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

    static int pow(int a, int b, int p)
    {
        long ans = 1, base = a;
        while (b!=0)
        {
            if ((b & 1)!=0)
            {
                ans *= base;
                ans%= p;
            }
            base *= base;
            base%= p;
            b >>= 1;
        }
        return (int)ans;
    }

    static int inv(int x, int p)
    {
        return pow(x, p - 2, p);
    }

    void run() throws Exception
    {
        if(codechef)oj=true;
        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 TimePass().run();}

    private byte[] inbuf = new byte[1024];
    public int lenbuf = 0, ptrbuf = 0;

    private int readByte()
    {
        if(lenbuf == -1)throw new InputMismatchException();
        if(ptrbuf >= lenbuf){
            ptrbuf = 0;
            try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
            if(lenbuf <= 0)return -1;
        }
        return inbuf[ptrbuf++];
    }

    private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
    private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }

    private double nd() { return Double.parseDouble(ns()); }
    private char nc() { return (char)skip(); }

    private String ns()
    {
        int b = skip();
        StringBuilder sb = new StringBuilder();
        while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
            sb.appendCodePoint(b);
            b = readByte();
        }
        return sb.toString();
    }

    private char[] ns(int n)
    {
        char[] buf = new char[n];
        int b = skip(), p = 0;
        while(p < n && !(isSpaceChar(b))){
            buf[p++] = (char)b;
            b = readByte();
        }
        return n == p ? buf : Arrays.copyOf(buf, p);
    }

    private char[][] nm(int n, int m)
    {
        char[][] map = new char[n][];
        for(int i = 0;i < n;i++)map[i] = ns(m);
        return map;
    }

    private int[] na(int n)
    {
        int[] a = new int[n];
        for(int i = 0;i < n;i++)a[i] = ni();
        return a;
    }

    private int ni()
    {
        int num = 0, b;
        boolean minus = false;
        while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
        if(b == '-'){
            minus = true;
            b = readByte();
        }

        while(true){
            if(b >= '0' && b <= '9'){
                num = num * 10 + (b - '0');
            }else{
                return minus ? -num : num;
            }
            b = readByte();
        }
    }

    private long nl()
    {
        long num = 0;
        int b;
        boolean minus = false;
        while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
        if(b == '-'){
            minus = true;
            b = readByte();
        }

        while(true){
            if(b >= '0' && b <= '9'){
                num = num * 10 + (b - '0');
            }else{
                return minus ? -num : num;
            }
            b = readByte();
        }
    }

    private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
    private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}

//package sept;

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

public class TimePass {
    InputStream is;
    PrintWriter out;
    String INPUT = "";
    //boolean codechef=true;
    boolean codechef=true;

	void solve()
	{
		int n=ni(),m=ni();
		int[] a=na(n);
		HashMap<Integer,Integer> map=new HashMap<>();
		int sum=0;
		for(int i=0;i<n;i++)
		{
			a[i]%=m;
			if(map.containsKey(a[i]))
			{
				map.put(a[i],map.get(a[i])+1);
			}
			else map.put(a[i], 1);
			sum+=a[i];
			sum%=m;
		}
		if(map.containsKey(m-1))
		{
			out.println(m-1);
			return;
		}
		int max=0;
		for(int i=0;i<Math.pow(2, n/2+1);i++)
		{
			int curr=i,s=0;
			int ind=n-1;
			while(curr!=0)
			{
				if(curr%2==1)s+=a[ind];
				s%=m;
				curr/=2;
				ind--;
			}
			max=Math.max(max, s);
			max=Math.max(max, (sum-s+m)%m);
		}
		out.println(max);
	}

	static int[][] packD(int n,int[] from,int[] to)
	{
		int[][] g=new int[n][];
		int[] p=new int[n];
		for(int f:from)
		{
			p[f]++;
		}
		int m=from.length;
		for(int i=0;i<n;i++)
		{
			g[i]=new int[p[i]];
		}
		for(int i=0;i<m;i++)
		{
			g[from[i]][--p[from[i]]]=to[i];
		}
		return g;
	}

    static class Pair
    {
        int a,b;
        public Pair(int a,int b)
        {
            this.a=a;
            this.b=b;
        }
    }

    static long lcm(int a,int b)
    {
        long val=a;
        val*=b;
        return (val/gcd(a,b));
    }

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

    static int pow(int a, int b, int p)
    {
        long ans = 1, base = a;
        while (b!=0)
        {
            if ((b & 1)!=0)
            {
                ans *= base;
                ans%= p;
            }
            base *= base;
            base%= p;
            b >>= 1;
        }
        return (int)ans;
    }

    static int inv(int x, int p)
    {
        return pow(x, p - 2, p);
    }

    void run() throws Exception
    {
        if(codechef)oj=true;
        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 TimePass().run();}

    private byte[] inbuf = new byte[1024];
    public int lenbuf = 0, ptrbuf = 0;

    private int readByte()
    {
        if(lenbuf == -1)throw new InputMismatchException();
        if(ptrbuf >= lenbuf){
            ptrbuf = 0;
            try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
            if(lenbuf <= 0)return -1;
        }
        return inbuf[ptrbuf++];
    }

    private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
    private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }

    private double nd() { return Double.parseDouble(ns()); }
    private char nc() { return (char)skip(); }

    private String ns()
    {
        int b = skip();
        StringBuilder sb = new StringBuilder();
        while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
            sb.appendCodePoint(b);
            b = readByte();
        }
        return sb.toString();
    }

    private char[] ns(int n)
    {
        char[] buf = new char[n];
        int b = skip(), p = 0;
        while(p < n && !(isSpaceChar(b))){
            buf[p++] = (char)b;
            b = readByte();
        }
        return n == p ? buf : Arrays.copyOf(buf, p);
    }

    private char[][] nm(int n, int m)
    {
        char[][] map = new char[n][];
        for(int i = 0;i < n;i++)map[i] = ns(m);
        return map;
    }

    private int[] na(int n)
    {
        int[] a = new int[n];
        for(int i = 0;i < n;i++)a[i] = ni();
        return a;
    }

    private int ni()
    {
        int num = 0, b;
        boolean minus = false;
        while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
        if(b == '-'){
            minus = true;
            b = readByte();
        }

        while(true){
            if(b >= '0' && b <= '9'){
                num = num * 10 + (b - '0');
            }else{
                return minus ? -num : num;
            }
            b = readByte();
        }
    }

    private long nl()
    {
        long num = 0;
        int b;
        boolean minus = false;
        while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
        if(b == '-'){
            minus = true;
            b = readByte();
        }

        while(true){
            if(b >= '0' && b <= '9'){
                num = num * 10 + (b - '0');
            }else{
                return minus ? -num : num;
            }
            b = readByte();
        }
    }

    private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
    private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}

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

public class tr0 {
	static PrintWriter out;
	static StringBuilder sb;
	static int mod = 1000000007;
	static long inf = (long) 1e16;
	static int[][] ad;
	static int n, m;
	static long[][][] memo;
	static HashSet<Integer> h;
	static long[] a;
	static HashSet<Integer> leaves;
	static TreeMap<pair, Long> dp;
	static ArrayList<Long> ar;

	public static void main(String[] args) throws Exception {
		Scanner sc = new Scanner(System.in);
		out = new PrintWriter(System.out);
		n = sc.nextInt();
		m = sc.nextInt();
		a = sc.nextArrLong(n);
		ar = new ArrayList<>();
		v = 0;
		cal(0);
		Collections.sort(ar);
		v = 0;
		ans = 0;
		cal2(n / 2);
		System.out.println(ans);
		out.close();
	}

	static long v, ans;

	static void cal(int i) {
		if (i == n / 2) {
			ans = Math.max(ans, v % mod);
			ar.add(v % mod);
			return;
		}
		cal(i + 1);
		v += a[i];
		cal(i + 1);
		v -= a[i];
	}

	static void cal2(int i) {
		if (i == n) {
			long x = v % m;
			ans = Math.max(ans, (x + ar.get(ar.size() - 1)) % m);
			int lo = 0;
			int hi = ar.size() - 1;
			long tem = 0;
			while (lo <= hi) {
				int mid = (lo + hi) >> 1;
				if (x + ar.get(mid) >= m) {
					hi = mid - 1;
				} else {
					tem = ar.get(mid);
					lo = mid + 1;
				}
			}
			ans = Math.max(ans, x + tem);
			return;
		}
		cal2(i + 1);
		v += a[i];
		cal2(i + 1);
		v -= a[i];
	}

	static class pair implements Comparable<pair> {
		int to;
		long number;

		pair(int t, long n) {
			number = n;
			to = t;
		}

		public String toString() {
			return to + " " + number;
		}

		@Override
		public int compareTo(pair o) {
			if (to == o.to)
				return Long.compare(number, o.number);
			return to - o.to;
		}

	}

	static class Scanner {
		StringTokenizer st;
		BufferedReader br;

		public Scanner(InputStream system) {
			br = new BufferedReader(new InputStreamReader(system));
		}

		public Scanner(String file) throws Exception {
			br = new BufferedReader(new FileReader(file));
		}

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

		public String nextLine() throws IOException {
			return br.readLine();
		}

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

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

		public char nextChar() throws IOException {
			return next().charAt(0);
		}

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

		public int[] nextArrInt(int n) throws IOException {
			int[] a = new int[n];
			for (int i = 0; i < n; i++)
				a[i] = nextInt();
			return a;
		}

		public long[] nextArrLong(int n) throws IOException {
			long[] a = new long[n];
			for (int i = 0; i < n; i++)
				a[i] = nextInt();
			return a;
		}

		public boolean ready() throws IOException {
			return br.ready();
		}

		public void waitForInput() throws InterruptedException {
			Thread.sleep(3000);
		}
	}
}

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

public class tr0 {
	static PrintWriter out;
	static StringBuilder sb;
	static int mod = 1000000007;
	static long inf = (long) 1e16;
	static int[][] ad;
	static int n, m;
	static long[][][] memo;
	static HashSet<Integer> h;
	static int[] a;
	static HashSet<Integer> leaves;
	static TreeMap<pair, Integer> dp;

	public static void main(String[] args) throws Exception {
		Scanner sc = new Scanner(System.in);
		out = new PrintWriter(System.out);
		n = sc.nextInt();
		m = sc.nextInt();
		a = sc.nextArrInt(n);
		dp=new TreeMap<>();
		System.out.println(d(0, 0));
		out.close();
	}

	static int d(int i, int l) {
		if (i == n)
			return 0;
		if (dp.containsKey(new pair(i, l)))
			return dp.get(new pair(i, l));
		int ans = d(i + 1, l);
		ans=Math.max((d(i+1,(l+a[i])%m)+a[i])%m, ans);
		dp.put(new pair(i, l), ans);
		return ans;
	}

	static class pair implements Comparable<pair> {
		int to;
		int number;

		pair(int t, int n) {
			number = n;
			to = t;
		}

		public String toString() {
			return to + " " + number;
		}

		@Override
		public int compareTo(pair o) {
			if (to == o.to)
				return number - o.number;
			return to - o.to;
		}

	}

	static class Scanner {
		StringTokenizer st;
		BufferedReader br;

		public Scanner(InputStream system) {
			br = new BufferedReader(new InputStreamReader(system));
		}

		public Scanner(String file) throws Exception {
			br = new BufferedReader(new FileReader(file));
		}

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

		public String nextLine() throws IOException {
			return br.readLine();
		}

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

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

		public char nextChar() throws IOException {
			return next().charAt(0);
		}

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

		public int[] nextArrInt(int n) throws IOException {
			int[] a = new int[n];
			for (int i = 0; i < n; i++)
				a[i] = nextInt();
			return a;
		}

		public long[] nextArrLong(int n) throws IOException {
			long[] a = new long[n];
			for (int i = 0; i < n; i++)
				a[i] = nextInt();
			return a;
		}

		public boolean ready() throws IOException {
			return br.ready();
		}

		public void waitForInput() throws InterruptedException {
			Thread.sleep(3000);
		}
	}
}

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

public class tr0 {
	static PrintWriter out;
	static StringBuilder sb;
	static int mod = 1000000007;
	static long inf = (long) 1e16;
	static int[][] ad;
	static int n, m;
	static long[][][] memo;
	static HashSet<Integer> h;
	static long[] a;
	static HashSet<Integer> leaves;
	static TreeMap<pair, Long> dp;

	public static void main(String[] args) throws Exception {
		Scanner sc = new Scanner(System.in);
		out = new PrintWriter(System.out);
		n = sc.nextInt();
		m = sc.nextInt();
		a = sc.nextArrLong(n);
		dp=new TreeMap<>();
		System.out.println(d(0, 0));
		out.close();
	}

	static long d(int i, long l) {
		if (i == n)
			return 0;
		if (dp.containsKey(new pair(i, l)))
			return dp.get(new pair(i, l));
		long ans = d(i + 1, l);
		ans=Math.max((d(i+1,(l+a[i])%m)+a[i])%m, ans);
		dp.put(new pair(i, l), ans);
		return ans;
	}

	static class pair implements Comparable<pair> {
		int to;
		long number;

		pair(int t, long n) {
			number = n;
			to = t;
		}

		public String toString() {
			return to + " " + number;
		}

		@Override
		public int compareTo(pair o) {
			if (to == o.to)
				return Long.compare(number, o.number);
			return to - o.to;
		}

	}

	static class Scanner {
		StringTokenizer st;
		BufferedReader br;

		public Scanner(InputStream system) {
			br = new BufferedReader(new InputStreamReader(system));
		}

		public Scanner(String file) throws Exception {
			br = new BufferedReader(new FileReader(file));
		}

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

		public String nextLine() throws IOException {
			return br.readLine();
		}

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

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

		public char nextChar() throws IOException {
			return next().charAt(0);
		}

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

		public int[] nextArrInt(int n) throws IOException {
			int[] a = new int[n];
			for (int i = 0; i < n; i++)
				a[i] = nextInt();
			return a;
		}

		public long[] nextArrLong(int n) throws IOException {
			long[] a = new long[n];
			for (int i = 0; i < n; i++)
				a[i] = nextInt();
			return a;
		}

		public boolean ready() throws IOException {
			return br.ready();
		}

		public void waitForInput() throws InterruptedException {
			Thread.sleep(3000);
		}
	}
}

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

public class tr0 {
	static PrintWriter out;
	static StringBuilder sb;
	static int mod = 1000000007;
	static long inf = (long) 1e16;
	static int[][] ad;
	static int n, m;
	static long[][][] memo;
	static HashSet<Integer> h;
	static long[] a;
	static HashSet<Integer> leaves;
	static TreeMap<pair, Long> dp;
	static ArrayList<Long> ar;

	public static void main(String[] args) throws Exception {
		Scanner sc = new Scanner(System.in);
		out = new PrintWriter(System.out);
		n = sc.nextInt();
		m = sc.nextInt();
		a = sc.nextArrLong(n);
		ar = new ArrayList<>();
		v = 0;
		cal(0);
		Collections.sort(ar);
		v = 0;
		ans = 0;
		cal2(n / 2);
		System.out.println(ans);
		out.close();
	}

	static long v, ans;

	static void cal(int i) {
		if (i == n / 2) {
			ans = Math.max(ans, v % mod);
			ar.add(v % mod);
			return;
		}
		cal(i + 1);
		v += a[i];
		cal(i + 1);
		v -= a[i];
	}

	static void cal2(int i) {
		if (i == n) {
			long x = v % m;
			ans = Math.max(ans, (x + ar.get(ar.size() - 1)) % m);
			int lo = 0;
			int hi = ar.size() - 1;
			long tem = 0;
			while (lo <= hi) {
				int mid = (lo + hi) >> 1;
				if (x + ar.get(mid) >= m) {
					hi = mid - 1;
				} else {
					tem = ar.get(mid);
					lo = mid + 1;
				}
			}
			ans = Math.max(ans, (x + tem) % mod);
			return;
		}
		cal2(i + 1);
		v += a[i];
		cal2(i + 1);
		v -= a[i];
	}

	static class pair implements Comparable<pair> {
		int to;
		long number;

		pair(int t, long n) {
			number = n;
			to = t;
		}

		public String toString() {
			return to + " " + number;
		}

		@Override
		public int compareTo(pair o) {
			if (to == o.to)
				return Long.compare(number, o.number);
			return to - o.to;
		}

	}

	static class Scanner {
		StringTokenizer st;
		BufferedReader br;

		public Scanner(InputStream system) {
			br = new BufferedReader(new InputStreamReader(system));
		}

		public Scanner(String file) throws Exception {
			br = new BufferedReader(new FileReader(file));
		}

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

		public String nextLine() throws IOException {
			return br.readLine();
		}

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

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

		public char nextChar() throws IOException {
			return next().charAt(0);
		}

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

		public int[] nextArrInt(int n) throws IOException {
			int[] a = new int[n];
			for (int i = 0; i < n; i++)
				a[i] = nextInt();
			return a;
		}

		public long[] nextArrLong(int n) throws IOException {
			long[] a = new long[n];
			for (int i = 0; i < n; i++)
				a[i] = nextLong();
			return a;
		}

		public boolean ready() throws IOException {
			return br.ready();
		}

		public void waitForInput() throws InterruptedException {
			Thread.sleep(3000);
		}
	}
}

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

public class tr0 {
	static PrintWriter out;
	static StringBuilder sb;
	static int mod = 1000000007;
	static long inf = (long) 1e16;
	static int[][] ad;
	static int n, m;
	static long[][][] memo;
	static HashSet<Integer> h;
	static long[] a;
	static HashSet<Integer> leaves;
	static TreeMap<pair, Long> dp;
	static ArrayList<Long> ar;

	public static void main(String[] args) throws Exception {
		Scanner sc = new Scanner(System.in);
		out = new PrintWriter(System.out);
		n = sc.nextInt();
		m = sc.nextInt();
		a = sc.nextArrLong(n);
		ar = new ArrayList<>();
		v = 0;
		cal(0);
		Collections.sort(ar);
		v = 0;
		ans = 0;
		cal2(n / 2);
		System.out.println(ans);
		out.close();
	}

	static long v, ans;

	static void cal(int i) {
		if (i == n / 2) {
			ar.add(v % mod);
			return;
		}
		cal(i + 1);
		v += a[i];
		cal(i + 1);
		v -= a[i];
	}

	static void cal2(int i) {
		if (i == n) {
			long x = v % m;
			ans = Math.max(ans, (x + ar.get(ar.size() - 1)) % m);
			int lo = 0;
			int hi = ar.size() - 1;
			long tem = 0;
			while (lo <= hi) {
				int mid = (lo + hi) >> 1;
				if (x + ar.get(mid) >= m) {
					hi = mid - 1;
				} else {
					tem = ar.get(mid);
					lo = mid + 1;
				}
			}
			ans = Math.max(ans, x + tem);
			return;
		}
		cal2(i + 1);
		v += a[i];
		cal2(i + 1);
		v -= a[i];
	}

	static class pair implements Comparable<pair> {
		int to;
		long number;

		pair(int t, long n) {
			number = n;
			to = t;
		}

		public String toString() {
			return to + " " + number;
		}

		@Override
		public int compareTo(pair o) {
			if (to == o.to)
				return Long.compare(number, o.number);
			return to - o.to;
		}

	}

	static class Scanner {
		StringTokenizer st;
		BufferedReader br;

		public Scanner(InputStream system) {
			br = new BufferedReader(new InputStreamReader(system));
		}

		public Scanner(String file) throws Exception {
			br = new BufferedReader(new FileReader(file));
		}

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

		public String nextLine() throws IOException {
			return br.readLine();
		}

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

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

		public char nextChar() throws IOException {
			return next().charAt(0);
		}

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

		public int[] nextArrInt(int n) throws IOException {
			int[] a = new int[n];
			for (int i = 0; i < n; i++)
				a[i] = nextInt();
			return a;
		}

		public long[] nextArrLong(int n) throws IOException {
			long[] a = new long[n];
			for (int i = 0; i < n; i++)
				a[i] = nextInt();
			return a;
		}

		public boolean ready() throws IOException {
			return br.ready();
		}

		public void waitForInput() throws InterruptedException {
			Thread.sleep(3000);
		}
	}
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.io.InputStream;

/**
 * Built using CHelper plug-in Actual solution is at the top
 *
 * @author MaxHeap
 */
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);
    MaximumSubsequence solver = new MaximumSubsequence();
    solver.solve(1, in, out);
    out.close();
  }

  static class MaximumSubsequence {

    public void solve(int testNumber, InputReader in, PrintWriter out) {
      int n = in.nextInt();
      int m = in.nextInt();
      int[] arr = in.nextIntArray(n);
      if (n == 1) {
        out.println(arr[0] % m);
        return;
      }

      ArrayList<Long> sumsL = new ArrayList<>();
      ArrayList<Long> sumsR = new ArrayList<>();

      long ans = 0;

      int mask = 1 << (n / 2);
      int omask = 1 << (n - (n / 2));

      for (int i = 1; i < mask; i++) {
        long cur = 0;
        for (int j = 0; j < n / 2; j++) {
          if ((i & (1 << j)) > 0) {
            cur += arr[j];
            cur %= m;
          }
        }
        sumsL.add(cur);
      }

      for (int i = 1; i < omask; i++) {
        long cur = 0;
        for (int j = n / 2; j < n; j++) {
          int ind = j - n / 2;
          if ((i & (1 << ind)) > 0) {
            cur += arr[j];
            cur %= m;
          }
        }
        sumsR.add(cur);
      }
      sumsL.sort(null);
      sumsR.sort(null);
      int l = 0, r = sumsR.size() - 1;
      while (l < sumsL.size()) {
        long to = m - sumsL.get(l) - 1;
        while (r >= 0 && sumsR.get(r) > to) {
          r--;
        }
        if (r >= 0) {
          ans = Math.max(sumsR.get(r) + sumsL.get(l), ans);
        }
        ++l;
      }
      out.println(ans);
    }

  }

  static class InputReader {

    private InputStream stream;
    private byte[] buf = new byte[1 << 13];
    private int curChar;
    private int numChars;

    public InputReader(InputStream stream) {
      this.stream = stream;
    }

    public int read() {
      if (this.numChars == -1) {
        throw new UnknownError();
      } else {
        if (this.curChar >= this.numChars) {
          this.curChar = 0;

          try {
            this.numChars = this.stream.read(this.buf);
          } catch (IOException ex) {
            throw new InputMismatchException();
          }

          if (this.numChars <= 0) {
            return -1;
          }
        }

        return this.buf[this.curChar++];
      }
    }

    public int nextInt() {
      int c;
      for (c = this.read(); isSpaceChar(c); c = this.read()) {
      }

      byte sgn = 1;
      if (c == 45) {
        sgn = -1;
        c = this.read();
      }

      int res = 0;

      while (c >= 48 && c <= 57) {
        res *= 10;
        res += c - 48;
        c = this.read();
        if (isSpaceChar(c)) {
          return res * sgn;
        }
      }

      throw new InputMismatchException();
    }

    public static boolean isSpaceChar(int c) {
      return c == 32 || c == 10 || c == 13 || c == 9 || c == -1;
    }

    public int[] nextIntArray(int n) {
      int[] arr = new int[n];
      for (int i = 0; i < n; i++) {
        arr[i] = nextInt();
      }
      return arr;
    }

  }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.io.InputStream;

/**
 * Built using CHelper plug-in Actual solution is at the top
 *
 * @author MaxHeap
 */
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);
    MaximumSubsequence solver = new MaximumSubsequence();
    solver.solve(1, in, out);
    out.close();
  }

  static class MaximumSubsequence {

    public void solve(int testNumber, InputReader in, PrintWriter out) {
      int n = in.nextInt();
      int m = in.nextInt();
      int[] arr = in.nextIntArray(n);

      ArrayList<Long> sumsL = new ArrayList<>();
      ArrayList<Long> sumsR = new ArrayList<>();

      long ans = 0;

      int mask = 1 << (n / 2);
      int omask = 1 << (n - (n / 2));

      for (int i = 1; i < mask; i++) {
        long cur = 0;
        for (int j = 0; j < n / 2; j++) {
          if ((i & (1 << j)) > 0) {
            cur += arr[j];
            cur %= m;
          }
        }
        sumsL.add(cur);
      }

      for (int i = 1; i < omask; i++) {
        long cur = 0;
        for (int j = n / 2; j < n; j++) {
          int ind = j - n / 2;
          if ((i & (1 << ind)) > 0) {
            cur += arr[j];
            cur %= m;
          }
        }
        sumsR.add(cur);
      }
      sumsL.sort(null);
      sumsR.sort(null);
      int l = 0, r = sumsR.size() - 1;
      while (l < sumsL.size()) {
        long to = m - sumsL.get(l) - 1;
        while (r >= 0 && sumsR.get(r) > to) {
          r--;
        }
        if (r >= 0) {
          ans = Math.max(sumsR.get(r) + sumsL.get(l), ans);
        }
        ++l;
      }
      out.println(ans);
    }

  }

  static class InputReader {

    private InputStream stream;
    private byte[] buf = new byte[1 << 13];
    private int curChar;
    private int numChars;

    public InputReader(InputStream stream) {
      this.stream = stream;
    }

    public int read() {
      if (this.numChars == -1) {
        throw new UnknownError();
      } else {
        if (this.curChar >= this.numChars) {
          this.curChar = 0;

          try {
            this.numChars = this.stream.read(this.buf);
          } catch (IOException ex) {
            throw new InputMismatchException();
          }

          if (this.numChars <= 0) {
            return -1;
          }
        }

        return this.buf[this.curChar++];
      }
    }

    public int nextInt() {
      int c;
      for (c = this.read(); isSpaceChar(c); c = this.read()) {
      }

      byte sgn = 1;
      if (c == 45) {
        sgn = -1;
        c = this.read();
      }

      int res = 0;

      while (c >= 48 && c <= 57) {
        res *= 10;
        res += c - 48;
        c = this.read();
        if (isSpaceChar(c)) {
          return res * sgn;
        }
      }

      throw new InputMismatchException();
    }

    public static boolean isSpaceChar(int c) {
      return c == 32 || c == 10 || c == 13 || c == 9 || c == -1;
    }

    public int[] nextIntArray(int n) {
      int[] arr = new int[n];
      for (int i = 0; i < n; i++) {
        arr[i] = nextInt();
      }
      return arr;
    }

  }
}

import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

/**
 * Created by shhuan on 2017/11/10.
 */
public class Main_888E {

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		int N = scanner.nextInt();
		int M = scanner.nextInt();

		scanner.nextLine();

		int[] A = Arrays.stream(scanner.nextLine().split(" ")).mapToInt(v -> Integer.parseInt(v)).toArray();

		if (N == 1){
			System.out.println(A[0] % M);
		} else {
			int lb = N / 2;
			int lc = N-lb;
			int[] B = new int[lb];
			int[] C = new int[lc];
			for (int i = 0; i < lb; i++) {
				B[i] = A[i];
			}
			for (int i = 0; i < lc; i++) {
				C[i] = A[i+lb];
			}

			Set<Integer> bs = new HashSet<>();
			bs.add(0);
			for (int i = 0; i < lb; i++) {
				Set<Integer> bd = new HashSet<>();
				for (Integer v : bs) {
					bd.add((v+B[i]) % M);
				}
				bs.addAll(bd);
			}

			Set<Integer> cs = new HashSet<>();
			cs.add(0);
			for (int i = 0; i < lc; i++) {
				Set<Integer> cd = new HashSet<>();
				for (Integer v : cs) {
					cd.add((v+C[i]) % M);
				}
				cs.addAll(cd);
			}

			int[] cs2 = cs.stream().mapToInt(v -> v).toArray();
			Arrays.sort(cs2);

			int ans = 0;
			for (int v: bs) {
				int k = 1;
				while (true) {
					int i = Arrays.binarySearch(cs2, k*M-v);
					if (i > 0) {
						ans = Math.max(ans, (v+cs2[i-1])%M);
					}
					if (0 <= i && i < cs2.length) {
						ans = Math.max(ans, (v+cs2[i]) % M);
					}
					if (i < 0 || i >= cs2.length) {
						break;
					}
					k += 1;
				}
			}

			System.out.println(ans);

		}
	}
}

import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

/**
 * Created by shhuan on 2017/11/10.
 */
public class Main_888E {

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		int N = scanner.nextInt();
		int M = scanner.nextInt();

		scanner.nextLine();

		int[] A = Arrays.stream(scanner.nextLine().split(" ")).mapToInt(v -> Integer.parseInt(v)).toArray();

		if (N == 1){
			System.out.println(A[0] % M);
		} else {
			int lb = N / 2;
			int lc = N-lb;
			int[] B = new int[lb];
			int[] C = new int[lc];
			for (int i = 0; i < lb; i++) {
				B[i] = A[i];
			}
			for (int i = 0; i < lc; i++) {
				C[i] = A[i+lb];
			}

			Set<Integer> bs = new HashSet<>();
			bs.add(0);
			for (int i = 0; i < lb; i++) {
				Set<Integer> bd = new HashSet<>();
				for (Integer v : bs) {
					bd.add((v+B[i]) % M);
				}
				bs.addAll(bd);
			}

			Set<Integer> cs = new HashSet<>();
			cs.add(0);
			for (int i = 0; i < lc; i++) {
				Set<Integer> cd = new HashSet<>();
				for (Integer v : cs) {
					cd.add((v+C[i]) % M);
				}
				cs.addAll(cd);
			}

			int[] cs2 = cs.stream().mapToInt(v -> v).toArray();
			Arrays.sort(cs2);

			int ans = 0;
			for (int v: bs) {
				int k = 1;
				while (true) {
					int i = Arrays.binarySearch(cs2, k*M-v-1);
					if (i > 0) {
						ans = Math.max(ans, (v+cs2[i-1])%M);
					}
					if (0 <= i && i < cs2.length) {
						ans = Math.max(ans, (v+cs2[i]) % M);
					}
					if (i < 0 || i >= cs2.length) {
						break;
					}
					k += 1;
				}
			}

			System.out.println(ans);

		}
	}
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

public class Main {

    public static void main(String[] args) {
        MyScanner in = new MyScanner();
        int n = in.nextInt();
        int m = in.nextInt();
        boolean[] arr = new boolean[m];
        boolean[] arr2 = new boolean[m];

        int max = 0;
        for (int i = 0; i < n; i++) {
            int v = in.nextInt() % m;
            if (v == m - 1) {
                System.out.println(m - 1);
                return;
            }
            max = Math.max(v, max);
            for (int j = 1; j < m; j++) {
                if (!arr[j]) continue;
                int v2 = (j + v) % m;
                if (arr[v2]) continue;
                max = Math.max(v2, max);
                if (v2 == m - 1) {
                    System.out.println(m - 1);
                    return;
                }
                arr2[v2] = true;
            }

            for (int j = 0; j < m; j++) {
                arr[i] |= arr2[i];
                arr2[i] = false;
            }

            arr[v] = true;
        }

        System.out.println(max);
    }

    public static int gcd(int a, int b) {
        int t;
        while (b != 0) {
            t = b;
            b = a % b;
            a = t;
        }
        return a;
    }

    public static void pa(List<Object> objs) {
        String str = "";
        for (Object obj : objs) {
            str += obj.toString() + " ";
        }
        p(str);
    }

    public static void pa(int[] objs) {
        String str = "";
        for (int i = 0; i < objs.length; i++) {
            str += objs[i] + " ";
        }
        p(str);
    }

    static void p(Object str) {
        System.out.println(str);
    }

    static class MyScanner {
        BufferedReader br;
        StringTokenizer st;

        public MyScanner() {
            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;
        }
    }
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

public class Main {

    public static void main(String[] args) {
        MyScanner in = new MyScanner();
        int n = in.nextInt();
        int m = in.nextInt();

        boolean[] arr = new boolean[m];
        int max = 0;
        for (int i = 0; i < n; i++) {
            int v = in.nextInt() % m;
            if (v == m - 1) {
                System.out.println(m - 1);
                return;
            }
            max = Math.max(v, max);
            for (int j = 1; j < m; j++) {
                if (!arr[j]) continue;
                int v2 = (j + v) % m;
                max = Math.max(v2, max);
                arr[v2] = true;
                if (v2 == m - 1) {
                    System.out.println(m - 1);
                    return;
                }
            }

            arr[v] = true;
        }

        System.out.println(max);
    }

    public static int gcd(int a, int b) {
        int t;
        while (b != 0) {
            t = b;
            b = a % b;
            a = t;
        }
        return a;
    }

    public static void pa(List<Object> objs) {
        String str = "";
        for (Object obj : objs) {
            str += obj.toString() + " ";
        }
        p(str);
    }

    public static void pa(int[] objs) {
        String str = "";
        for (int i = 0; i < objs.length; i++) {
            str += objs[i] + " ";
        }
        p(str);
    }

    static void p(Object str) {
        System.out.println(str);
    }

    static class MyScanner {
        BufferedReader br;
        StringTokenizer st;

        public MyScanner() {
            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;
        }
    }
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

public class Main {

    public static void main(String[] args) {
        MyScanner in = new MyScanner();
        int n = in.nextInt();
        int m = in.nextInt();

        boolean[] arr = new boolean[m];
        int max = 0;
        for (int i = 0; i < n; i++) {
            int v = in.nextInt() % m;
            if (v == m - 1) {
                System.out.println(m - 1);
                return;
            }
            max = Math.max(v, max);
            List<Integer> toAdd = new ArrayList<>();
            for (int j = 1; j < m; j++) {
                if (!arr[j]) continue;
                int v2 = (j + v) % m;
                max = Math.max(v2, max);
                if (v2 == m - 1) {
                    System.out.println(m - 1);
                    return;
                }
                if (!arr[v2]) {
                    toAdd.add(j);
                }
            }

            for (Integer p: toAdd) arr[p] = true;

            arr[v] = true;
        }

        System.out.println(max);
    }

    public static int gcd(int a, int b) {
        int t;
        while (b != 0) {
            t = b;
            b = a % b;
            a = t;
        }
        return a;
    }

    public static void pa(List<Object> objs) {
        String str = "";
        for (Object obj : objs) {
            str += obj.toString() + " ";
        }
        p(str);
    }

    public static void pa(int[] objs) {
        String str = "";
        for (int i = 0; i < objs.length; i++) {
            str += objs[i] + " ";
        }
        p(str);
    }

    static void p(Object str) {
        System.out.println(str);
    }

    static class MyScanner {
        BufferedReader br;
        StringTokenizer st;

        public MyScanner() {
            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;
        }
    }
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

public class Main {

    public static void main(String[] args) {
        MyScanner in = new MyScanner();
        int n = in.nextInt();
        int m = in.nextInt();

        boolean[] arr = new boolean[m];
        boolean[] arr2 = new boolean[m];
        int max = 0;
        for (int i = 0; i < n; i++) {
            int v = in.nextInt() % m;
            if (v == m - 1) {
                System.out.println(m - 1);
                return;
            }
            max = Math.max(v, max);
            for (int j = 1; j < m; j++) {
                if (!arr[j]) continue;
                int v2 = (j + v) % m;
                if (arr[v2]) continue;
                max = Math.max(v2, max);
                if (v2 == m - 1) {
                    System.out.println(m - 1);
                    return;
                }
                arr2[v2] = true;
            }

            for (int j = 0; j < m; j++) {
                arr[i] |= arr2[i];
                arr2[i] = false;
            }

            arr[v] = true;
        }

        System.out.println(max);
    }

    public static int gcd(int a, int b) {
        int t;
        while (b != 0) {
            t = b;
            b = a % b;
            a = t;
        }
        return a;
    }

    public static void pa(List<Object> objs) {
        String str = "";
        for (Object obj : objs) {
            str += obj.toString() + " ";
        }
        p(str);
    }

    public static void pa(int[] objs) {
        String str = "";
        for (int i = 0; i < objs.length; i++) {
            str += objs[i] + " ";
        }
        p(str);
    }

    static void p(Object str) {
        System.out.println(str);
    }

    static class MyScanner {
        BufferedReader br;
        StringTokenizer st;

        public MyScanner() {
            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;
        }
    }
}