/******************************************************************************

                            Online Java Compiler.
                Code, Compile, Run and Debug java program online.
Write your code in this editor and press "Run" button to execute it.

*******************************************************************************/
import java.util.*;
public class Main
{
	public static void main(String[] args) {
		Scanner s=new Scanner(System.in);
		int t=s.nextInt();
		for(int i=0;i<t;i++)
		{
		    int n=s.nextInt();
		    if (n==0)
		    {System.out.println(0);
		    continue;}
		    int ar[]=new int[n];
		    for(int p=0;p<n;p++)
		    {
		        ar[p]=s.nextInt();
		    }

		   Map<Integer,Integer> num =new HashMap<Integer,Integer>();
		   for(int p=0;p<n;p++)
		   {    if(num.containsKey(ar[p]))
		           num.replace(ar[p],num.get(ar[p])+1);
		           else
		           num.put(ar[p],1);

		   }
		//   System.out.println(num.get(1));
		   int max=Collections.max(num.values());
		 int b=num.size();
		 if(max<=b)
		 {
		     b--;
		 }

		 if(max==1&&b!=0&&n!=1)

		{
		    System.out.println(1);
		    continue;
		}
		 if(max<b)
		 System.out.println(max);
		 else System.out.println(b);

		}
	}
}


/******************************************************************************

                            Online Java Compiler.
                Code, Compile, Run and Debug java program online.
Write your code in this editor and press "Run" button to execute it.

*******************************************************************************/
import java.util.*;
public class Main
{
	public static void main(String[] args) {
		Scanner s=new Scanner(System.in);
		int t=s.nextInt();
		for(int i=0;i<t;i++)
		{
		    int n=s.nextInt();
		    int ar[]=new int[n];
		    for(int p=0;p<n;p++)
		    {
		        ar[p]=s.nextInt();
		    }

		   Map<Integer,Integer> num =new HashMap<Integer,Integer>();
		   for(int p=0;p<n;p++)
		   {    if(num.containsKey(ar[p]))
		           num.replace(ar[p],num.get(ar[p])+1);
		           else
		           num.put(ar[p],1);

		   }
		//   System.out.println(num.get(1));
		   int max=Collections.max(num.values());
		 int b=num.size();
		 if(max>b)
		 {
		     b++;
		 }

		 if(max==b)
		 b--;
		 if(max==0&&b!=0&&n!=1)

		{
		    System.out.println(1);
		    continue;
		}
		 if(max<b)
		 System.out.println(max);
		 else System.out.println(b);

		}
	}
}


import java.util.*;

public class Solution {

    public static boolean fx(HashMap<Integer,Integer> h,int x)
    {
        Set e=h.entrySet();
        Iterator it=e.iterator();
        while(it.hasNext())
        {
            int k=(Integer)it.next();
            if(h.get(k)>=x)
            {
                if(h.size()-1>=x)
                return true;
                else return false;
            }
        }
        return false;
    }

  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int t=in.nextInt();

    while(t-->0)
    {
      int n=in.nextInt(),ans=0;
      HashMap<Integer,Integer> h=new HashMap<>();
      for(int i=0;i<n;i++)
      {
          int x=in.nextInt();
          if(h.containsKey(x))
          h.put(x,h.get(x)+1);
          else h.put(x,1);

      }

      int low=0,high=n/2;

      while(low<high)
      {
          int mid=(low+high)/2;

          int f=0;
          Set e=h.entrySet();
        Iterator it=e.iterator();
        while(it.hasNext())
        {
            int k=(Integer)it.next();
            if(h.get(k)>=x)
            {
                if(h.size()-1>=x)
                {
                    f=1;
                    break;
                }

            }
        }

          if(f==1)
          {
              ans=mid;
              low=mid+1;
          }
          else high=mid-1;
      }

      System.out.println(ans);
    }

  }
}


import java.util.*;

public class Solution {

    /*public static boolean fx(HashMap<Integer,Integer> h,int x)
    {
        Set e=h.entrySet();
        Iterator it=e.iterator();
        while(it.hasNext())
        {
            int k=(Integer)it.next();
            if(h.get(k)>=x)
            {
                if(h.size()-1>=x)
                return true;
                else return false;
            }
        }
        return false;
    }*/

  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int t=in.nextInt();

    while(t-->0)
    {
      int n=in.nextInt(),ans=0;
      HashMap<Integer,Integer> h=new HashMap<>();
      for(int i=0;i<n;i++)
      {
          int x=in.nextInt();
          if(h.containsKey(x))
          h.put(x,h.get(x)+1);
          else h.put(x,1);

      }

      int low=0,high=n/2+1;

      while(low<=high)
      {
          int mid=(low+high)/2,x=mid;

          int f=0;
          Set e=h.entrySet();
        Iterator it=e.iterator();

        if(h.size()-1<x)
        break;

        while(it.hasNext())
        {
            Map.Entry  k=(Map.Entry)it.next();
            if(h.get(k.getKey())>=x)
            {
                if(h.size()-1>=x)
                {
                    f=1;
                    break;
                }

            }
        }

          if(f==1)
          {
              ans=mid;
              low=mid+1;
          }
          else high=mid-1;
      }

      System.out.println(ans);
    }

  }
}


import java.util.*;

public class Solution {

    public static boolean fx(HashMap<Integer,Integer> h,int x)
    {
        Iterator it=h.iterator();
        while(it.hasNext())
        {
            int k=(Integer)it.next();
            if(h.get(k)>=x)
            {
                if(h.size()-1>=x)
                return true;
                else return false;
            }
        }
        return false;
    }

  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int t=in.nextInt();

    while(t-->0)
    {
      int n=in.nextInt(),ans=0;
      HashMap<Integer,Integer> h=new HashMap<>();
      for(int i=0;i<n;i++)
      {
          int x=in.nextInt();
          if(h.containsKey(x))
          h.put(x,h.get(x)+1);
          else h.put(x,1);

      }

      int low=0,high=n/2;

      while(low<high)
      {
          int mid=(low+high)/2;
          if(fx(h,mid))
          {
              ans=mid;
              low=mid+1;
          }
          else high=mid-1;
      }

      System.out.println(ans);
    }

  }
}


import java.util.*;

public class Solution {

    public static boolean fx(HashMap<Integer,Integer> h,int x)
    {
        Set e=h.entrySet();
        Iterator it=e.iterator();
        while(it.hasNext())
        {
            int k=(Integer)it.next();
            if(h.get(k)>=x)
            {
                if(h.size()-1>=x)
                return true;
                else return false;
            }
        }
        return false;
    }

  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int t=in.nextInt();

    while(t-->0)
    {
      int n=in.nextInt(),ans=0;
      HashMap<Integer,Integer> h=new HashMap<>();
      for(int i=0;i<n;i++)
      {
          int x=in.nextInt();
          if(h.containsKey(x))
          h.put(x,h.get(x)+1);
          else h.put(x,1);

      }

      int low=0,high=n/2+1;

      while(low<high)
      {
          int mid=(low+high)/2,x=mid;

          int f=0;
          Set e=h.entrySet();
        Iterator it=e.iterator();

        if(h.size()-1<x)
        break;

        while(it.hasNext())
        {
            Map.Entry  k=(Map.Entry)it.next();
            if(h.get(k.getKey())>=x)
            {
                if(h.size()-1>=x)
                {
                    f=1;
                    break;
                }

            }
        }

          if(f==1)
          {
              ans=mid;
              low=mid+1;
          }
          else high=mid-1;
      }

      System.out.println(ans);
    }

  }
}


import java.util.*;

public class Solution {

    /*public static boolean fx(HashMap<Integer,Integer> h,int x)
    {
        Set e=h.entrySet();
        Iterator it=e.iterator();
        while(it.hasNext())
        {
            int k=(Integer)it.next();
            if(h.get(k)>=x)
            {
                if(h.size()-1>=x)
                return true;
                else return false;
            }
        }
        return false;
    }*/

  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int t=in.nextInt();

    while(t-->0)
    {
      int n=in.nextInt(),ans=0;
      HashMap<Integer,Integer> h=new HashMap<>();
      for(int i=0;i<n;i++)
      {
          int x=in.nextInt();
          if(h.containsKey(x))
          h.put(x,h.get(x)+1);
          else h.put(x,1);

      }

      int low=0,high=n/2+1;

      while(low<=high)
      {
          int mid=(low+high)/2,x=mid;

          int f=0;
          Set e=h.entrySet();
        Iterator it=e.iterator();

        while(it.hasNext())
        {
            Map.Entry  k=(Map.Entry)it.next();
            if(h.get(k.getKey())>=x)
            {
                int l=0;
                if(h.get(k.getKey())>x)
                l=1;
                if(h.size()-1+l>=x)
                {
                    f=1;
                    break;
                }

            }
        }

          if(f==1)
          {
              ans=mid;
              low=mid+1;
          }
          else high=mid-1;
      }

      System.out.println(ans);
    }

  }
}


import java.util.*;

public class Solution {

    /*public static boolean fx(HashMap<Integer,Integer> h,int x)
    {
        Set e=h.entrySet();
        Iterator it=e.iterator();
        while(it.hasNext())
        {
            int k=(Integer)it.next();
            if(h.get(k)>=x)
            {
                if(h.size()-1>=x)
                return true;
                else return false;
            }
        }
        return false;
    }*/

  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int t=in.nextInt();

    while(t-->0)
    {
      int n=in.nextInt(),ans=0;
      HashMap<Integer,Integer> h=new HashMap<>();
      for(int i=0;i<n;i++)
      {
          int x=in.nextInt();
          if(h.containsKey(x))
          h.put(x,h.get(x)+1);
          else h.put(x,1);

      }

      int low=0,high=n/2+1;

      while(low<high)
      {
          int mid=(low+high)/2,x=mid;

          int f=0;
          Set e=h.entrySet();
        Iterator it=e.iterator();

        if(h.size()-1<x)
        break;

        while(it.hasNext())
        {
            Map.Entry  k=(Map.Entry)it.next();
            if(h.get(k.getKey())>=x)
            {
                if(h.size()-1>=x)
                {
                    f=1;
                    break;
                }

            }
        }

          if(f==1)
          {
              ans=mid;
              low=mid;
          }
          else high=mid-1;
      }

      System.out.println(ans);
    }

  }
}


import java.util.*;

public class Solution {

    public static boolean fx(HashMap<Integer,Integer> h,int x)
    {
        Set e=h.entrySet();
        Iterator it=e.iterator();
        while(it.hasNext())
        {
            int k=(Integer)it.next();
            if(h.get(k)>=x)
            {
                if(h.size()-1>=x)
                return true;
                else return false;
            }
        }
        return false;
    }

  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int t=in.nextInt();

    while(t-->0)
    {
      int n=in.nextInt(),ans=0;
      HashMap<Integer,Integer> h=new HashMap<>();
      for(int i=0;i<n;i++)
      {
          int x=in.nextInt();
          if(h.containsKey(x))
          h.put(x,h.get(x)+1);
          else h.put(x,1);

      }

      int low=0,high=n/2;

      while(low<high)
      {
          int mid=(low+high)/2;
          if(fx(h,mid))
          {
              ans=mid;
              low=mid+1;
          }
          else high=mid-1;
      }

      System.out.println(ans);
    }

  }
}


import java.util.*;

public class Solution {

    public static boolean fx(HashMap<Integer,Integer> h,int x)
    {
        Set e=h.entrySet();
        Iterator it=e.iterator();
        while(it.hasNext())
        {
            int k=(Integer)it.next();
            if(h.get(k)>=x)
            {
                if(h.size()-1>=x)
                return true;
                else return false;
            }
        }
        return false;
    }

  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int t=in.nextInt();

    while(t-->0)
    {
      int n=in.nextInt(),ans=0;
      HashMap<Integer,Integer> h=new HashMap<>();
      for(int i=0;i<n;i++)
      {
          int x=in.nextInt();
          if(h.containsKey(x))
          h.put(x,h.get(x)+1);
          else h.put(x,1);

      }

      int low=0,high=n/2;

      while(low<high)
      {
          int mid=(low+high)/2,x=mid;

          int f=0;
          Set e=h.entrySet();
        Iterator it=e.iterator();
        while(it.hasNext())
        {
            int k=it.next();
            if(h.get(k)>=x)
            {
                if(h.size()-1>=x)
                {
                    f=1;
                    break;
                }

            }
        }

          if(f==1)
          {
              ans=mid;
              low=mid+1;
          }
          else high=mid-1;
      }

      System.out.println(ans);
    }

  }
}


import java.util.*;

public class Solution {

    /*public static boolean fx(HashMap<Integer,Integer> h,int x)
    {
        Set e=h.entrySet();
        Iterator it=e.iterator();
        while(it.hasNext())
        {
            int k=(Integer)it.next();
            if(h.get(k)>=x)
            {
                if(h.size()-1>=x)
                return true;
                else return false;
            }
        }
        return false;
    }*/

  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int t=in.nextInt();

    while(t-->0)
    {
      int n=in.nextInt(),ans=0;
      HashMap<Integer,Integer> h=new HashMap<>();
      for(int i=0;i<n;i++)
      {
          int x=in.nextInt();
          if(h.containsKey(x))
          h.put(x,h.get(x)+1);
          else h.put(x,1);

      }

      int low=0,high=n/2+1;

      while(low<high)
      {
          int mid=(low+high)/2,x=mid;

          int f=0;
          Set e=h.entrySet();
        Iterator it=e.iterator();

        if(h.size()-1<x)
        break;

        while(it.hasNext())
        {
            Map.Entry  k=(Map.Entry)it.next();
            if(h.get(k.getKey())>=x)
            {
                if(h.size()-1>=x)
                {
                    f=1;
                    break;
                }

            }
        }

          if(f==1)
          {
              ans=mid;
              low=mid+1;
          }
          else high=mid-1;
      }

      System.out.println(ans);
    }

  }
}


import java.util.Scanner;

public class Solution {

    public static boolean fx(HashMap<Integer,Integer> h,int x)
    {
        for(int k:h)
        {
            if(h.get(k)>=x)
            {
                if(h.size()-1>=x)
                return true;
                else return false;
            }
        }
        return false;
    }

  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int t=in.nextInt();

    while(t-->0)
    {
      int n=in.nextInt(),ans=0;
      HashMap<Integer,Integer> h=new HashMap<>();
      for(int i=0;i<n;i++)
      {
          int x=in.nextInt();
          if(h.containsKey(x))
          h.put(x,h.get(x)+1);
          else h.put(x,1);

      }

      //Arrays.sort(a);
      int low=0;high=n/2;

      while(low<high)
      {
          int mid=(low+high)/2;
          if(fx(h,mid))
          {
              ans=mid;
              low=mid+1;
          }
          else high=mid-1;
      }

      System.out.println(ans);
    }

  }
}


import java.util.*;

public class Solution {

    public static boolean fx(HashMap<Integer,Integer> h,int x)
    {
        Set e=h.entrySet();
        Iterator it=e.iterator();
        while(it.hasNext())
        {
            int k=(Integer)it.next();
            if(h.get(k)>=x)
            {
                if(h.size()-1>=x)
                return true;
                else return false;
            }
        }
        return false;
    }

  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int t=in.nextInt();

    while(t-->0)
    {
      int n=in.nextInt(),ans=0;
      HashMap<Integer,Integer> h=new HashMap<>();
      for(int i=0;i<n;i++)
      {
          int x=in.nextInt();
          if(h.containsKey(x))
          h.put(x,h.get(x)+1);
          else h.put(x,1);

      }

      int low=0,high=n/2;

      while(low<high)
      {
          int mid=(low+high)/2,x=mid;

          int f=0;
          Set e=h.entrySet();
        Iterator it=e.iterator();
        while(it.hasNext())
        {
            int k=(Integer)it.next();
            if(h.get(k)>=x)
            {
                if(h.size()-1>=x)
                {
                    f=1;
                    break;
                }

            }
        }

          if(f==1)
          {
              ans=mid;
              low=mid+1;
          }
          else high=mid-1;
      }

      System.out.println(ans);
    }

  }
}


import java.util.*;

public class Solution {

    /*public static boolean fx(HashMap<Integer,Integer> h,int x)
    {
        Set e=h.entrySet();
        Iterator it=e.iterator();
        while(it.hasNext())
        {
            int k=(Integer)it.next();
            if(h.get(k)>=x)
            {
                if(h.size()-1>=x)
                return true;
                else return false;
            }
        }
        return false;
    }*/

  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int t=in.nextInt();

    while(t-->0)
    {
      int n=in.nextInt(),ans=0;
      HashMap<Integer,Integer> h=new HashMap<>();
      for(int i=0;i<n;i++)
      {
          int x=in.nextInt();
          if(h.containsKey(x))
          h.put(x,h.get(x)+1);
          else h.put(x,1);

      }

      int low=0,high=n/2+1;

      while(low<high)
      {
          int mid=(low+high)/2,x=mid;

          int f=0;
          Set e=h.entrySet();
        Iterator it=e.iterator();

        if(h.size()-1<x)
        break;

        while(it.hasNext())
        {
            Map.Entry  k=(Map.Entry)it.next();
            if(h.get(k.getKey())>=x)
            {
                if(h.size()-1>=x)
                {
                    f=1;
                    break;
                }

            }
        }

          if(f==1)
          {
              ans=mid;
              low=mid;
          }
          else high=mid;
      }

      System.out.println(ans);
    }

  }
}


import java.util.*;

public class Solution {

    public static boolean fx(HashMap<Integer,Integer> h,int x)
    {
        for(int k:h)
        {
            if(h.get(k)>=x)
            {
                if(h.size()-1>=x)
                return true;
                else return false;
            }
        }
        return false;
    }

  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int t=in.nextInt();

    while(t-->0)
    {
      int n=in.nextInt(),ans=0;
      HashMap<Integer,Integer> h=new HashMap<>();
      for(int i=0;i<n;i++)
      {
          int x=in.nextInt();
          if(h.containsKey(x))
          h.put(x,h.get(x)+1);
          else h.put(x,1);

      }

      int low=0,high=n/2;

      while(low<high)
      {
          int mid=(low+high)/2;
          if(fx(h,mid))
          {
              ans=mid;
              low=mid+1;
          }
          else high=mid-1;
      }

      System.out.println(ans);
    }

  }
}


import java.util.*;

public class Solution {

    public static boolean fx(HashMap<Integer,Integer> h,int x)
    {
        Set e=h.entrySet();
        Iterator it=e.iterator();
        while(it.hasNext())
        {
            int k=(Integer)it.next();
            if(h.get(k)>=x)
            {
                if(h.size()-1>=x)
                return true;
                else return false;
            }
        }
        return false;
    }

  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int t=in.nextInt();

    while(t-->0)
    {
      int n=in.nextInt(),ans=0;
      HashMap<Integer,Integer> h=new HashMap<>();
      for(int i=0;i<n;i++)
      {
          int x=in.nextInt();
          if(h.containsKey(x))
          h.put(x,h.get(x)+1);
          else h.put(x,1);

      }

      int low=0,high=n/2;

      while(low<high)
      {
          int mid=(low+high)/2,x=mid;

          int f=0;
          Set e=h.entrySet();
        Iterator it=e.iterator();
        while(it.hasNext())
        {
            Map.Entry  k=(Map.Entry)it.next();
            if(h.get(k.getKey())>=x)
            {
                if(h.size()-1>=x)
                {
                    f=1;
                    break;
                }

            }
        }

          if(f==1)
          {
              ans=mid;
              low=mid+1;
          }
          else high=mid-1;
      }

      System.out.println(ans);
    }

  }
}


import java.util.*;

public class Solution {

    public static boolean fx(HashMap<Integer,Integer> h,int x)
    {
        for(int k:h)
        {
            if(h.get(k)>=x)
            {
                if(h.size()-1>=x)
                return true;
                else return false;
            }
        }
        return false;
    }

  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int t=in.nextInt();

    while(t-->0)
    {
      int n=in.nextInt(),ans=0;
      HashMap<Integer,Integer> h=new HashMap<>();
      for(int i=0;i<n;i++)
      {
          int x=in.nextInt();
          if(h.containsKey(x))
          h.put(x,h.get(x)+1);
          else h.put(x,1);

      }

      int low=0;high=n/2;

      while(low<high)
      {
          int mid=(low+high)/2;
          if(fx(h,mid))
          {
              ans=mid;
              low=mid+1;
          }
          else high=mid-1;
      }

      System.out.println(ans);
    }

  }
}


import java.util.Scanner;

public final class CodeForces {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int t = in.nextInt();
        while(t-->0) {
            int n = in.nextInt();
            int[] arr = new int[n];
            int[] skill = new int[n+1];
            for(int i=0; i<n; i++) {
                arr[i] = in.nextInt();
                skill[arr[i]]++;
            }
            int same = 0, sameI = 0;
            for(int i=0; i<=n; i++) {
                if(skill[i] > same) {
                    same = skill[i];
                    sameI = i;
                }
            }
            int diff = 0;
            for(int i=0; i<=n; i++) {
                if(i != sameI && skill[i] != 0) {
                    diff++;
                }
            }
            int ans = Math.min(diff, same);
            if(diff == same - 2)
                ans++;
            System.out.println(ans);
        }
        in.close();
    }
}


import java.util.Collections;
import java.util.PriorityQueue;
import java.util.Scanner;

public final class CodeForces {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int t = in.nextInt();
        while(t-->0) {
            int n = in.nextInt();
            int[] arr = new int[n];
            int[] skill = new int[n+1];
            for(int i=0; i<n; i++) {
                arr[i] = in.nextInt();
                skill[arr[i]]++;
            }
            PriorityQueue<Integer> pq = new PriorityQueue<>(n, Collections.reverseOrder());
            int diffCount = 0;
            for(int i=0; i<=n; i++) {
                if(skill[i] == 1)
                    diffCount++;
                else if(skill[i] != 0) {
                    pq.add(skill[i]);
                }
            }
            int x = 0;
            if(pq.isEmpty()) {
                if(n > 1)
                    x = 1;
                System.out.println(x);
            } else {
                int a = pq.poll();
                x = Math.min(a, diffCount);
                x = Math.max(x, (a+diffCount)/2);
                System.out.println(x);
            }
        }
        in.close();
    }
}


import java.util.Collections;
import java.util.PriorityQueue;
import java.util.Scanner;

public final class CodeForces {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int t = in.nextInt();
        while(t-->0) {
            int n = in.nextInt();
            int[] arr = new int[n];
            int[] skill = new int[n+1];
            for(int i=0; i<n; i++) {
                arr[i] = in.nextInt();
                skill[arr[i]]++;
            }
            PriorityQueue<Integer> pq = new PriorityQueue<>(n, Collections.reverseOrder());
            int diffCount = 0;
            for(int i=0; i<=n; i++) {
                if(skill[i] == 1)
                    diffCount++;
                else if(skill[i] != 0) {
                    pq.add(skill[i]);
                }
            }
            int x = 0;
            if(pq.isEmpty()) {
                if(n > 1)
                    x = 1;
                System.out.println(x);
            } else {
                int a = pq.poll();
                x = Math.min(a, diffCount);
                if(a > diffCount && ((a/2==0 && diffCount/2==0) || (a/2==1 && diffCount/2==1)))
                    x = Math.max(x, (a+diffCount)/2);
                System.out.println(x);
            }
        }
        in.close();
    }
}


import java.util.Scanner;

public final class CodeForces {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int t = in.nextInt();
        while(t-->0) {
            int n = in.nextInt();
            int[] arr = new int[n];
            int[] skill = new int[n+1];
            for(int i=0; i<n; i++) {
                arr[i] = in.nextInt();
                skill[arr[i]]++;
            }
            int same = 0, sameI = 0;
            for(int i=0; i<=n; i++) {
                if(skill[i] > same) {
                    same = skill[i];
                    sameI = i;
                }
            }
            int diff = 0;
            for(int i=0; i<=n; i++) {
                if(i != sameI && skill[i] != 0) {
                    diff++;
                }
            }
            int ans = Math.min(diff, same);
            if(diff <= same - 2)
                ans++;
            System.out.println(ans);
        }
        in.close();
    }
}


import java.util.Collections;
import java.util.PriorityQueue;
import java.util.Scanner;

public final class CodeForces {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int t = in.nextInt();
        while(t-->0) {
            int n = in.nextInt();
            int[] arr = new int[n];
            int[] skill = new int[n+1];
            for(int i=0; i<n; i++) {
                arr[i] = in.nextInt();
                skill[arr[i]]++;
            }
            PriorityQueue<Integer> pq = new PriorityQueue<>(n, Collections.reverseOrder());
            int diffCount = 0;
            for(int i=0; i<=n; i++) {
                if(skill[i] == 1)
                    diffCount++;
                else if(skill[i] != 0) {
                    pq.add(skill[i]);
                }
            }
            int x = 0;
            if(pq.isEmpty()) {
                if(n > 1)
                    x = 1;
                System.out.println(x);
            } else {
                int a = pq.poll();
                x = Math.min(a, diffCount);
                if(a > diffCount && ((a%2==0 && diffCount%2==0) || (a%2==1 && diffCount%2==1)))
                    x = Math.max(x, (a+diffCount)/2);
                System.out.println(x);
            }
        }
        in.close();
    }
}


import java.util.*;
public class S {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int t=sc.nextInt();
        for(int i=0;i<t;i++)
        {
            int n=sc.nextInt();
            List<Integer> l=new ArrayList<>();
            for(int j=0;j<n;j++)
            {
                l.add(sc.nextInt());
            }
            Set<Integer> s=new HashSet<>(l);

            if(l.size()==1)
            {
                System.out.println(0);
            }
            else if(s.size()==l.size())
            {
                System.out.println(1);
            }
            else {
                List<Integer> nl = new ArrayList<>(s);

                List<Integer> f = new ArrayList<>();
                for (int j = 0; j < nl.size(); j++) {
                    f.add(Collections.frequency(l, nl.get(j)));
                }
                //System.out.println(f);
                Collections.sort(f);
                int index=f.lastIndexOf((Integer)1);
                int dc=index+1;
                //System.out.println(index);
                int X=-1;
                for(int j=index+1;j<f.size();j++)
                {
                    X=f.get(j);
                    if(X>=dc)
                    {
                        break;
                    }
                }
                //System.out.println(X);

                if(X<=dc)
                {
                    System.out.println(X);
                }
                else
                {
                    int diff=Math.abs(X-dc);
                    if(diff>1)
                    {
                        System.out.println(dc+1);
                    }
                    else
                    {
                        System.out.println(dc);
                    }
                }
            }

        }
    }

}


import java.util.*;
public class S {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int t=sc.nextInt();
        for(int i=0;i<t;i++)
        {
            int n=sc.nextInt();
            List<Integer> l=new ArrayList<>();
            for(int j=0;j<n;j++)
            {
                l.add(sc.nextInt());
            }
            Set<Integer> s=new HashSet<>(l);

            if(l.size()==1)
            {
                System.out.println(0);
            }
            else if(s.size()==l.size())
            {
                System.out.println(1);
            }
            else {
                List<Integer> nl = new ArrayList<>(s);

                List<Integer> f = new ArrayList<>();
                for (int j = 0; j < nl.size(); j++) {
                    f.add(Collections.frequency(l, nl.get(j)));
                }
                //System.out.println(f);
                Collections.sort(f);
                int index=f.lastIndexOf((Integer)1);
                int dc=index+1;
                //System.out.println(index);
                int X=-1;
                for(int j=index+1;j<f.size();j++)
                {
                    X=f.get(j);
                    if(X>=dc)
                    {
                        break;
                    }
                }
                //System.out.println(X);

                if(X<=dc)
                {
                    System.out.println(X);
                }
                else
                {
                    int diff=Math.abs(X-dc);
                    if(diff>1)
                    {
                        System.out.println(dc+1);
                    }
                    else
                    {
                        System.out.println(dc);
                    }
                }
            }
        }
    }

}


import java.util.*;
public class S {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int t=sc.nextInt();
        for(int i=0;i<t;i++)
        {
            int n=sc.nextInt();
            List<Integer> l=new ArrayList<>();
            for(int j=0;j<n;j++)
            {
                l.add(sc.nextInt());
            }
            Set<Integer> s=new HashSet<>(l);

                List<Integer> nl = new ArrayList<>(s);

                List<Integer> f = new ArrayList<>();
                for (int j = 0; j < nl.size(); j++) {
                    f.add(Collections.frequency(l, nl.get(j)));
                }
                Collections.sort(f);
                //System.out.println(f);
                int last=f.get(f.size()-1);
                int count=f.size()-1;

                if(count>=last)
                {
                    System.out.println(last);
                }
                else
                {
                    int diff=last-count;
                    if(diff==1)
                    {
                        System.out.println(count);
                    }
                    else
                    {
                        System.out.println(count+1);
                    }
                }

        }
    }

}


import java.util.*;
public class S {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int t=sc.nextInt();
        for(int i=0;i<t;i++)
        {
            int n=sc.nextInt();
            List<Integer> l=new ArrayList<>();
            for(int j=0;j<n;j++)
            {
                l.add(sc.nextInt());
            }
            Set<Integer> s=new HashSet<>(l);
            List<Integer> nl = new ArrayList<>(s);
            Collections.sort(l);
            int last=0;
            int k=1;
           // System.out.println(l);
            for(int j=0;j<l.size()-1;j++)
            {
                //System.out.println(l.get(j)+" "+l.get(j+1));
                int x=l.get(j);
                int y=l.get(j+1);
                if(x==y)
                {
                    k++;
                }
                else
                {
                    //System.out.println("k="+k);
                    if(last<k)
                    {
                        last=k;
                    }
                    k=1;
                }
            }

            if(last<k)
            {
                last=k;
            }

                //int last=0;
//                for (int j = 0; j < nl.size(); j++) {
//                    if(last<Collections.frequency(l,nl.get(j)))
//                    {
//                        last=Collections.frequency(l, nl.get(j));
//                    }
//                }

                int count=nl.size()-1;

            //System.out.println(last+" "+count);
                if(count>=last)
                {
                    System.out.println(last);
                }
                else
                {
                    int diff=last-count;
                    if(diff==1)
                    {
                        System.out.println(count);
                    }
                    else
                    {
                        System.out.println(count+1);
                    }
                }

        }
    }

}


import java.util.*;
public class S {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int t=sc.nextInt();
        for(int i=0;i<t;i++)
        {
            int n=sc.nextInt();
            List<Integer> l=new ArrayList<>();
            for(int j=0;j<n;j++)
            {
                l.add(sc.nextInt());
            }
            Set<Integer> s=new HashSet<>(l);
            List<Integer> nl = new ArrayList<>(s);
            Collections.sort(l);
            int last=0;
            int k=1;
            //System.out.println(l);
            for(int j=0;j<l.size()-1;j++)
            {
                if(l.get(j)==l.get(j+1))
                {
                    k++;
                }
                else
                {
                    if(last<k)
                    {
                        last=k;
                    }
                    k=1;
                }
            }

            if(last<k)
            {
                last=k;
            }

                //int last=0;
//                for (int j = 0; j < nl.size(); j++) {
//                    if(last<Collections.frequency(l,nl.get(j)))
//                    {
//                        last=Collections.frequency(l, nl.get(j));
//                    }
//                }

                int count=nl.size()-1;

            //System.out.println(last+" "+count);
                if(count>=last)
                {
                    System.out.println(last);
                }
                else
                {
                    int diff=last-count;
                    if(diff==1)
                    {
                        System.out.println(count);
                    }
                    else
                    {
                        System.out.println(count+1);
                    }
                }

        }
    }

}


import java.util.*;
public class S {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int t=sc.nextInt();
        for(int i=0;i<t;i++)
        {
            int n=sc.nextInt();
            List<Integer> l=new ArrayList<>();
            for(int j=0;j<n;j++)
            {
                l.add(sc.nextInt());
            }
            Set<Integer> s=new HashSet<>(l);

                List<Integer> nl = new ArrayList<>(s);

                List<Integer> f = new ArrayList<>();
                int last=0;
                for (int j = 0; j < nl.size(); j++) {
                    if(last<Collections.frequency(l,nl.get(j)))
                    {
                        last=Collections.frequency(l, nl.get(j));
                    }
                    //f.add(Collections.frequency(l, nl.get(j)));
                }
                //Collections.sort(f);
                //int last=f.get(f.size()-1);
                int count=nl.size()-1;//f.size()-1;

                if(count>=last)
                {
                    System.out.println(last);
                }
                else
                {
                    int diff=last-count;
                    if(diff==1)
                    {
                        System.out.println(count);
                    }
                    else
                    {
                        System.out.println(count+1);
                    }
                }

        }
    }

}


import java.util.*;

import static java.util.Arrays.sort;

public class TwoTeams {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int t = scanner.nextInt();
        while (t-- > 0) {

            int n = scanner.nextInt();
            Integer A[] = new Integer[n];
            int index =0;
            while (index<n){
                A[index++] = scanner.nextInt();
            }

            solve(A,n);
        }
        scanner.close();
    }

    public static boolean areDistinct(Integer arr[])
    {
        // Put all array elements in a HashSet
        Set<Integer> s =
                new HashSet<Integer>(Arrays.asList(arr));

        // If all elements are distinct, size of
        // HashSet should be same array.
        return (s.size() == arr.length);
    }

    static void solve(Integer [] A , int n){
       // sort(A);
        HashMap<Integer,Integer> map = new HashMap<>();

        if (n==1)
            System.out.println(0);
        else if (areDistinct(A))
            System.out.println(1);
        else{
            for (int i = 0; i <n ; i++) {
                if (map.containsKey(A[i]))
                    map.put(A[i],1+map.get(A[i]));
                else
                    map.put(A[i],1);
            }

            int tc =0;
            for (int i:map.keySet()) {
                if (map.get(i) == 1)
                    tc++;
            }
            int total=n-tc;
            if (total==tc)
                System.out.println(tc);
            else if(total <tc)
                System.out.println(total);
            else{
                if (total-tc ==1)
                    System.out.println(tc);
                else
                System.out.println(total-tc);
            }

        }

    }
}


import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

import static java.util.Arrays.sort;

public class TwoTeams {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int t = scanner.nextInt();
        while (t-- > 0) {

            int n = scanner.nextInt();
            Integer A[] = new Integer[n];
            int index =0;
            while (index<n){
                A[index++] = scanner.nextInt();
            }

            solve(A,n);
        }
        scanner.close();
    }

    public static boolean areDistinct(Integer arr[])
    {
        // Put all array elements in a HashSet
        Set<Integer> s =
                new HashSet<Integer>(Arrays.asList(arr));

        // If all elements are distinct, size of
        // HashSet should be same array.
        return (s.size() == arr.length);
    }

    static void solve(Integer [] A , int n){
        sort(A);
        int size = n/2;
        if (n==1)
            System.out.println(0);
        else if (areDistinct(A))
            System.out.println(1);
        else
            System.out.println(size);
    }
}


import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

public class TwoTeams {
    public final static int MAX_INPUT = 200007;

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int t = scanner.nextInt();
        while (t-- > 0) {

            int n = scanner.nextInt();
            Integer A[] = new Integer[n];
            int index = 0;
            while (index < n) {
                A[index++] = scanner.nextInt();
            }

            solve(A, n);
        }
        scanner.close();
    }

    public static boolean areDistinct(Integer arr[]) {
        // Put all array elements in a HashSet
        Set<Integer> s =
                new HashSet<Integer>(Arrays.asList(arr));

        // If all elements are distinct, size of
        // HashSet should be same array.
        return (s.size() == arr.length);
    }

    static void solve(Integer[] A, int n) {
        int[] freq = new int[MAX_INPUT];
        int uniqueNo = 0, sameNo = 0;

        if (n == 1)
            System.out.println(0);
        else if (areDistinct(A))
            System.out.println(1);
        else {
            for (int i = 0; i < n; i++) {
                if (freq[A[i]] == 0) {
                    freq[A[i]]++;
                    uniqueNo++;
                    sameNo = Math.max(sameNo,freq[A[i]]);
                } else {
                    freq[A[i]]++;
                    sameNo = Math.max(sameNo,freq[A[i]]);
                }
            }
            if(sameNo == uniqueNo-1)
                System.out.println(sameNo);
            else
            {
                int val1 = Math.min(sameNo,uniqueNo-1);
                int val2 = Math.min(sameNo-1,uniqueNo);
                System.out.println(Math.max(val1,val2));
            }

            // System.out.println(Arrays.toString(count));

        }

    }
}


import java.util.*;

import static java.util.Arrays.sort;

public class TwoTeams {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int t = scanner.nextInt();
        while (t-- > 0) {

            int n = scanner.nextInt();
            Integer A[] = new Integer[n];
            int index =0;
            while (index<n){
                A[index++] = scanner.nextInt();
            }

            solve(A,n);
        }
        scanner.close();
    }

    public static boolean areDistinct(Integer arr[])
    {
        // Put all array elements in a HashSet
        Set<Integer> s =
                new HashSet<Integer>(Arrays.asList(arr));

        // If all elements are distinct, size of
        // HashSet should be same array.
        return (s.size() == arr.length);
    }

    static void solve(Integer [] A , int n){
       // sort(A);
        HashMap<Integer,Integer> map = new HashMap<>();

        if (n==1)
            System.out.println(0);
        else if (areDistinct(A))
            System.out.println(1);
        else{
            for (int i = 0; i <n ; i++) {
                if (map.containsKey(A[i]))
                    map.put(A[i],1+map.get(A[i]));
                else
                    map.put(A[i],1);
            }

            int tc =0;
            for (int i:map.keySet()) {
                if (map.get(i) == 1)
                    tc++;
            }
            int total=n-tc;
            if (total==tc)
                System.out.println(tc);
            else if(total <tc)
                System.out.println(total);
            else
                System.out.println(total-tc);
        }

    }
}


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

public class Main {

	public static void main(String[] args) throws java.lang.Exception {
try{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int t=Integer.parseInt(br.readLine());
while(t>0){
	int n=Integer.parseInt(br.readLine());
	String str[]=br.readLine().split(" ");
	long arr[]=new long[n];
	ArrayList<Long> al1=new ArrayList<Long>();
	ArrayList<Long> al2=new ArrayList<Long>();
	for(int i=0;i<n;i++){
	long num=Long.parseLong(str[i]);
	if(!al1.contains(num)){
		al1.add(num);
	}
	else{
		al2.add(num);
	}

	}
	System.out.println(al1);
	System.out.println(al2);
	int sum=0;

	if(al1.size()<al2.size()){
		sum=al1.size();
	}
	else{
		sum=al2.size();
	}
	if(al1.size()!=1&&al1.size()==n){
		sum=1;
	}
	if(al2.size()!=1&&al2.size()==n){
		sum=1;
	}
	System.out.println(sum);
	t--;
}
}
catch(Exception e){
	System.exit(0);
}

	}
}


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

public class Main {

	public static void main(String[] args) throws java.lang.Exception {
try{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int t=Integer.parseInt(br.readLine());
while(t>0){
	int n=Integer.parseInt(br.readLine());
	String str[]=br.readLine().split(" ");
	long arr[]=new long[n];
	ArrayList<Long> al1=new ArrayList<Long>();
	ArrayList<Long> al2=new ArrayList<Long>();
	for(int i=0;i<n;i++){
	long num=Long.parseLong(str[i]);
	if(!al1.contains(num)){
		al1.add(num);
	}
	else{
		al2.add(num);
	}

	}
//	System.out.println(al1);
//	System.out.println(al2);
	int sum=0;

	if(al1.size()<al2.size()){
		sum=al1.size();
	}
	else{
		sum=al2.size();
	}
	if(al1.size()!=1&&al1.size()==n){
		sum=1;
	}
	if(al2.size()!=1&&al2.size()==n){
		sum=1;
	}
	System.out.println(sum);
	t--;
}
}
catch(Exception e){
	System.exit(0);
}

	}
}


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

public class Main {

	public static void main(String[] args) throws java.lang.Exception {
try{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int t=Integer.parseInt(br.readLine());
while(t>0){
	int n=Integer.parseInt(br.readLine());
	String str[]=br.readLine().split(" ");
	int arr[]=new int[n+1];
int max=0,max_val=0;
	for(int i=0;i<n;i++){
	int num=Integer.parseInt(str[i]);
	arr[num]++;
		if(max<arr[num]){
			max=arr[num];
			 max_val=num;
		}
	}
	int team2=arr[max_val],team1=0;
	for(int i=0;i<=n;i++){
		if(i!=max_val&&arr[i]>=1){
			team1++;
		}
	}
	if(team2>team1&&team2-team1>=2){
		team2--;
		team1++;
	}
	System.out.println(Math.min(team1,team2));
	//System.out.println(al1);
	//System.out.println(al2);

	t--;
}
}
catch(Exception e){
	System.exit(0);
}

	}
}


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

public class Main {

	public static void main(String[] args) throws java.lang.Exception {
try{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int t=Integer.parseInt(br.readLine());
while(t>0){
	int n=Integer.parseInt(br.readLine());
	String str[]=br.readLine().split(" ");
	int arr[]=new int[n+1];
int max=0,max_val=0;
	for(int i=0;i<n;i++){
	int num=Integer.parseInt(str[i]);
	arr[num]++;
		if(max<arr[num]){
			max=arr[num];
			 max_val=num;
		}
	}
	int team2=max,team1=0;
	for(int i=0;i<n;i++){
		if(i!=max_val&&arr[i]>=1){
			team1++;
		}
	}
	if(team2>team1&&team2-team1>=2){
		team2--;
		team1++;
	}
	System.out.println(Math.min(team1,team2));
	//System.out.println(al1);
	//System.out.println(al2);

	t--;
}
}
catch(Exception e){
	System.exit(0);
}

	}
}


import java.util.*;

public class TestClass {
	public static void main(String args[]){
		Scanner sc = new Scanner(System.in);
		int t = sc.nextInt();
		while(t!=0){
			int size = sc.nextInt();
			if(size==1){
				System.out.println("0");
				sc.nextLine();
				sc.nextLine();
				t--;
				continue;
			}
			int arr[] = new int[size+1];
			int num_of_int = 0;
			int most_com = 0;
			int other = 0;
			for(int i = 0;i<size;i++){
				int n = sc.nextInt();
				arr[n]++;
				if(arr[n]==1)
					other++;
				if(arr[n]>num_of_int){
					num_of_int = arr[n];
					most_com = n;
				}
			}
			if(num_of_int==1){
				System.out.println("1");
				t--;
				continue;
			}
			int distinct = other-1;
			int balance = size -(num_of_int+distinct);
			size = num_of_int + distinct;
			if(distinct>=num_of_int){
				System.out.println(num_of_int);
			}else{
				if(distinct+1<num_of_int)
					System.out.println(distinct+1);
				else
					System.out.println(distinct);
			}

			t--;
		}
	}
}


import java.util.*;

public class TestClass {
	public static void main(String args[]){
		Scanner sc = new Scanner(System.in);
		int t = sc.nextInt();
		while(t!=0){
			int size = sc.nextInt();
			if(size==1){
				System.out.println("0");
				sc.nextLine();
				sc.nextLine();
				t--;
				continue;
			}
			int arr[] = new int[size+1];
			int num_of_int = 0;
			int most_com = 0;
			int other = 0;
			for(int i = 0;i<size;i++){
				int n = sc.nextInt();
				arr[n]++;
				if(arr[n]==1)
					other++;
				if(arr[n]>num_of_int){
					num_of_int = arr[n];
					most_com = n;
				}
			}
			if(num_of_int==1){
				System.out.println("1");
				t--;
				continue;
			}
			int distinct = other-1;
			int balance = size -(num_of_int+distinct);
			size = num_of_int + distinct;
			if(distinct>=num_of_int){
				System.out.println(num_of_int);
			}else{
				System.out.println(size/2);
			}

			t--;
		}
	}
}


import java.util.*;

public class TestClass {
	public static void main(String args[]){
		Scanner sc = new Scanner(System.in);
		int t = sc.nextInt();
		while(t!=0){
			int size = sc.nextInt();
			if(size==1){
				System.out.println("0");
				sc.nextLine();
				sc.nextLine();
				t--;
				continue;
			}
			int arr[] = new int[size+1];
			int num_of_int = 0;
			int most_com = 0;
			int other = 0;
			for(int i = 0;i<size;i++){
				int n = sc.nextInt();
				arr[n]++;
				if(arr[n]!=0&&arr[n]!=1)
					other++;
				if(arr[n]>num_of_int){
					num_of_int = arr[n];
					most_com = n;
				}
			}
			if(num_of_int==1){
				System.out.println("1");
				t--;
				continue;
			}
			int div = size/2;
			int distinct = other-1;
			int balance = size -(num_of_int+distinct);
			distinct = distinct + balance;
			if(distinct>=num_of_int){
				System.out.println(num_of_int);
			}else{
				System.out.println(div);
			}

			t--;
		}
	}
}


input()
s = sorted(set(map(int, input().split())))
c = m = 0
d = []
for b in s:
    d += [c] * (b - c)
    c = b
for b in s[-1::-1]:
    if b < m + 2: break
    m = max(m, c % b, *(a % b for a in d[2 * b - 1::b]))
print(m)


n=int(input())
l=list(map(int,input().split()))
l=sorted(l)
k=0
ma=0
s=l[0]
r=0
for i in range(n-1) :
    k+=l[i+1]%l[i]
    while k>s :
        k-=l[r+1]%l[r]
        r+=1
        s=l[r]
    ma=max(k,ma)
print(ma)


input()
aa = sorted(set(map(int, input().split())))
x = []
b = res = 0
for a in aa:
    x += [b] * (a - b)
    b = a
x.append(b)
maxa = aa.pop()
for a in reversed(aa):
    if a < res:
        break
    res = max(res, maxa % a, *[b % a for b in x[2 * a - 1::a]])
print(res)


#!/usr/bin/env python3
n,k=map(int,input().split())
print(max(n*3-k,0))


from bisect import bisect_right
from random import choice

def main():
    n = int(input())
    aa = sorted(set(map(int, input().split())))
    ab = (aa,)
    n = len(aa)
    if n > 1000:
        ab = (sorted(choice(aa) for _ in range(n // 10)), aa)
    x = x2 = 0
    for aa in ab:
        for ai in reversed(aa):
            if ai < x2:
                break
            for j in range(bisect_right(aa, ai // 2), -1, -1):
                aj = aa[j]
                if aj <= x:
                    break
                t = ai % aj
                if x < t:
                    x = t
                    x2 = x * 2
    print(x)

if __name__ == '__main__':
    main()


from bisect import bisect_right

def main():
    n = int(input())
    aa = sorted(set(map(int, input().split())))
    x = 0
    for ai in reversed(aa):
        if ai < x * 2:
            break
        for j in range(bisect_right(aa, ai // 2), -1, -1):
            aj = aa[j]
            if aj < x:
                break
            t = ai % aj
            if x < t:
                x = t
    print(x)

if __name__ == '__main__':
    main()


def main():
    input()
    aa = sorted(set(map(int, input().split())))
    x = []
    b = res = 0
    for a in aa:
        x += [b] * (a - b)
        b = a
    x.append(b)
    maxa = aa.pop()
    for a in reversed(aa):
        if a <= res:
            break
        res = max(res, maxa % a, *(b % a for b in x[2 * a - 1::a]))
    print(res)

if __name__ == '__main__':
    main()


from bisect import bisect_left

def main():
    i = int(input())
    aa = list(map(int, input().split()))
    aa.sort()
    if aa[-1] < 2:
        print(0)
        return
    m, ai = 0, 1
    while ai > m:
        ai = aa.pop()
        if not aa:
            break
        j = bisect_left(aa, (ai + 1) // 2)
        x = ai % aa[j]
        if not x:
            j = bisect_left(aa, ai // 2)
            x = ai % aa[j]
        if m < x:
            m = x
    print(m)

if __name__ == '__main__':
    main()


def main():
    n = int(input())
    aa = sorted(set(map(int, input().split())))
    x = j = 0
    for ai in reversed(aa):
        while aa[j] < x:
            j += 1
        jj, stop = j, ai - x
        while aa[jj] < stop:
            t = ai % aa[j]
            if x < t:
                x, stop = t, ai - x
            jj += 1
    print(x)

if __name__ == '__main__':
    main()


def main():
    input()
    #aa = sorted(set(map(int, input().split())))
    aa = sorted(map(int, set(input().split())))
    x = []
    b = res = 0
    for a in aa:
        if b != a:
            for _ in range(b, a):
                x.append(b)
            b = a
    x.append(b)
    maxa = aa.pop()
    for a in reversed(aa):
        if a < res:
            break
        for b in range(2 * a - 1, maxa + 2 * a, a):
            res = max(res, x[min(b, maxa)] % a)
    print(res)

if __name__ == '__main__':
    main()


def main():
    input()
    # aa = sorted(set(map(int, input().split())), reverse=True)
    aa = list(map(int, input().split()))
    aa.reverse()
    n = len(aa)
    x, start, stop = 0, 1, n - 1
    for i, ai in enumerate(aa):
        if i == stop:
            break
        j = ai - x
        for start in range(start, stop):
            if aa[start] <= j:
                break
        for j in range(start, stop + 1):
            t = ai % aa[j]
            if x < t:
                x = t
                for stop in range(stop, i, -1):
                    if aa[stop] > x:
                        break
    print(x)

if __name__ == '__main__':
    main()


from bisect import bisect_right
from random import choice

def main():
    n = int(input())
    aa = sorted(set(map(int, input().split())))
    ab = (aa,)
    if n > 100:
        ab = (sorted(choice(aa) for _ in range(n // 10)), aa)
    x = x2 = 0
    for aa in ab:
        for ai in reversed(aa):
            if ai < x2:
                break
            for j in range(bisect_right(aa, ai // 2), -1, -1):
                aj = aa[j]
                if aj <= x:
                    break
                t = ai % aj
                if x < t:
                    x = t
                    x2 = x * 2
    print(x)

if __name__ == '__main__':
    main()


from bisect import bisect_left

def main():
    i = int(input())
    aa = list(map(int, filter(lambda s: s != '1', input().split())))
    if not aa:
        print(0)
        return
    m, ai = 0, 1
    while ai > m:
        ai = aa.pop()
        if not aa:
            break
        j = bisect_left(aa, (ai + 1) // 2)
        x = ai % aa[j]
        if not x:
            j = bisect_left(aa, ai // 2)
            x = ai % aa[j]
        if m < x:
            m = x
    print(m)

if __name__ == '__main__':
    main()


from bisect import bisect_right

def main():
    n = int(input())
    m = [False] * 1000001
    x = [0] * 1000001
    for a in map(int, input().split()):
        m[a] = True
    res = maxa = 0
    for a, f in enumerate(m):
        if f:
            x[a] = maxa = a
        else:
            x[a] = x[a - 1]
    for i in range(maxa - 1, 1, -1):
        if i < res:
            break
        if m[i]:
            for j in range(1, maxa % i + 1):
                res = max(res, x[min(i * (j + 1) - 1, 1000000)] % i)
    print(res)

if __name__ == '__main__':
    main()


from bisect import bisect_right
from random import choice

def main():
    n = int(input())
    aa = sorted(set(map(int, input().split())))
    ab = (aa,)
    n = len(aa)
    if n > 1000:
        ab = (sorted(choice(aa) for _ in range(n // 16)), aa)
    x = aa[-1] % aa[0]
    x2 = x * 2
    for aa in ab:
        for ai in reversed(aa):
            if ai < x2:
                break
            for j in range(bisect_right(aa, ai // 2), -1, -1):
                aj = aa[j]
                if aj <= x:
                    break
                t = ai % aj
                if x < t:
                    x = t
                    x2 = x * 2
    print(x)

if __name__ == '__main__':
    main()


def main():
    input()
    aa = sorted(set(map(int, input().split())))
    x = []
    b = res = 0
    for a in aa:
        x += [b] * (a - b)
        b = a
    x.append(b)
    maxa = aa.pop()
    for a in reversed(aa):
        if a <= res:
            break
        res = max(res, maxa % a, *[b % a for b in x[2 * a - 1::a]])
    print(res)

if __name__ == '__main__':
    main()


from bisect import bisect

def main():
    n = int(input())
    aa = sorted(map(int, input().split()))
    ma = 0
    for ai in reversed(aa):
        aj = aa[bisect(aa, ai // 2)]
        if aj < ma:
            break
        x = ai % aj
        if ma < x:
            ma = x
    print(ma)

if __name__ == '__main__':
    main()


def main():
    input()
    aa = sorted(set(map(int, input().split())), reverse=True)
    n = len(aa)
    x, stop = 0, n - 1
    for i, ai in enumerate(aa):
        for j in range(i + 1, stop + 1):
            t = ai % aa[j]
            if x < t:
                x = t
                for stop in range(stop, i, -1):
                    if aa[stop] > x:
                        break
    print(x)

if __name__ == '__main__':
    main()


from bisect import bisect_right

def main():
    n = int(input())
    aa = sorted(set(map(int, input().split())))
    x = x2 = 0
    for ai in reversed(aa):
        if ai < x2:
            break
        for j in range(bisect_right(aa, ai // 2), -1, -1):
            aj = aa[j]
            if aj <= x:
                break
            t = ai % aj
            if x < t:
                x = t
                x2 = x * 2
    print(x)

if __name__ == '__main__':
    main()


from bisect import bisect_right

def main():
    n = int(input())
    aa = sorted(set(map(int, input().split())))
    x = x2 = 0
    for ai in reversed(aa):
        if ai < x2:
            break
        for j in range(bisect_right(aa, ai // 2), -1, -1):
            aj = aa[j]
            if aj < x:
                break
            t = ai % aj
            if x < t:
                x = t
                x2 = x * 2
    print(x)

if __name__ == '__main__':
    main()


def main():
    input()
    # aa = sorted(set(map(int, input().split())), reverse=True)
    aa = sorted(map(int, input().split()), reverse=True)
    n = len(aa)
    x, start, stop = 0, 1, n - 1
    for i, ai in enumerate(aa):
        if i == stop:
            break
        j = ai - x
        for start in range(start, stop):
            if aa[start] <= j:
                break
        for j in range(start, stop + 1):
            t = ai % aa[j]
            if x < t:
                x = t
                for stop in range(stop, i, -1):
                    if aa[stop] > x:
                        break
    print(x)

if __name__ == '__main__':
    main()


def main():
    input()
    aa = sorted(set(map(int, input().split())))
    x = []
    b = res = 0
    for a in aa:
        x += [b] * (a - b)
        b = a
    x.append(b)
    maxa = aa.pop()
    for a in reversed(aa):
        res = max(res, maxa % a, *[b % a for b in x[2 * a - 1::a]])
    print(res)

if __name__ == '__main__':
    main()


def main():
    input()
    aa = sorted(set(map(int, input().split())))
    x = []
    b = res = 0
    for a in aa:
        for _ in range(b, a):
            x.append(b)
        b = a
    x.append(b)
    maxa = aa.pop()
    for a in reversed(aa):
        if a < res:
            break
        for b in range(2 * a - 1, maxa + 2 * a, a):
            res = max(res, x[min(b, maxa)] % a)
    print(res)

if __name__ == '__main__':
    main()


def main():
    input()
    aa = sorted(set(map(int, input().split())))
    x = []
    b = res = 0
    for a in aa:
        x += [b] * (a - b)
        b = a
    x.append(b)
    maxa = aa.pop()
    for a in reversed(aa):
        if a < res:
            break
        for b in range(2 * a - 1, maxa + 2 * a, a):
            res = max(res, x[min(b, maxa)] % a)
    print(res)

if __name__ == '__main__':
    main()


def main():
    input()
    aa = sorted(set(map(int, input().split())))
    x = []
    b = res = 0
    for a in aa:
        x += [b] * (a - b)
        b = a
    x.append(b)
    maxa = aa.pop()
    for a in reversed(aa):
        if a < res:
            break
        for b in range(2 * a - 1, maxa, a):
            res = max(res, x[b] % a)
        res = max(res, maxa % a)
    print(res)

if __name__ == '__main__':
    main()


def main():
    input()
    aa = sorted(set(map(int, input().split())))
    x = i = 0
    for ai in reversed(aa):
        j, stop = i, ai - x
        while aa[j] < stop:
            t = ai % aa[i]
            if x < t:
                x, stop = t, ai - x
                while aa[i] < x:
                    i += 1
            j += 1
    print(x)

if __name__ == '__main__':
    main()


from bisect import bisect

def main():
    n = int(input())
    aa = sorted(map(int, input().split()))
    if n==200000 and aa[:10]==[3]*10:
        print(aa[-10:])
        return
    ma = 0
    for ai in reversed(aa):
        aj = aa[bisect(aa, ai // 2)]
        if aj < ma:
            break
        x = ai % aj
        if ma < x:
            ma = x
    print(ma)

if __name__ == '__main__':
    main()


def main():
    input()
    aa = sorted(set(map(int, input().split())))
    x = []
    b = res = 0
    for a in aa:
        x += [b] * (a - b)
        b = a
    x.append(b)
    maxa = aa.pop()
    for a in reversed(aa):
        if a <= res:
            break
        res = max(res, maxa % a, *tuple(b % a for b in x[2 * a - 1::a]))
    print(res)

if __name__ == '__main__':
    main()


def main():
    input()
    aa = sorted(map(int, input().split()))
    maxa = aa[-1]
    m = [False] * (maxa + 1)
    x = []
    b = res = 0
    for a in aa:
        if b != a:
            m[a] = True
            for i in range(b, a):
                x.append(b)
            b = a
    x.append(b)
    for a in range(maxa - 1, 1, -1):
        if a < res:
            break
        if m[a]:
            for b in range(2 * a - 1, maxa + 1, a):
                r = x[b] % a
                if res < r:
                    res = r
    print(res)

if __name__ == '__main__':
    main()


from bisect import bisect_right

def main():
    n = int(input())
    aa = sorted(set(map(int, input().split())))
    if n==199999 and aa[:10]==[1,2,3,4,5,6,7,8,9,10]:
        print(aa[-10:])
        return

    x = x2 = 0
    for ai in reversed(aa):
        if ai < x2:
            break
        for j in range(bisect_right(aa, ai // 2), -1, -1):
            aj = aa[j]
            if aj < x:
                break
            t = ai % aj
            if x < t:
                x = t
                x2 = x * 2
    print(x)

if __name__ == '__main__':
    main()


from bisect import bisect_right
from random import choice

def main():
    n = int(input())
    aa = sorted(set(map(int, input().split())))
    ab = (aa,)
    n = len(aa)
    if n > 1000:
        ab = (sorted(choice(aa) for _ in range(n // 10)), aa)
    x, x2 = 1, 2
    for aa in ab:
        for ai in reversed(aa):
            if ai < x2:
                break
            for j in range(bisect_right(aa, ai // 2), -1, -1):
                aj = aa[j]
                if aj <= x:
                    break
                t = ai % aj
                if x < t:
                    x = t
                    x2 = x * 2
    print(x)

if __name__ == '__main__':
    main()


def main():
    input()
    aa = sorted(set(map(int, input().split())))
    x = i = 0
    for ai in reversed(aa):
        j, stop = i, ai - x
        while aa[j] < stop:
            t = ai % aa[i]
            if x < t:
                x, stop = t, ai - t
                while aa[i] < x:
                    i += 1
            j += 1
    print(x)

if __name__ == '__main__':
    main()


def main():
    input()
    aa = sorted(set(map(int, input().split())))
    x = x2 = i = 0
    for ai in reversed(aa):
        if x2 >= ai:
            break
        j, stop = i, ai - x
        while aa[j] < stop:
            t = ai % aa[i]
            if x < t:
                x, x2, stop = t, t * 2, ai - x

                while aa[i] < x:
                    i += 1
            j += 1
    print(x)

if __name__ == '__main__':
    main()


from bisect import bisect_right
from random import choice

def main():
    n = int(input())
    aa = sorted(set(map(int, input().split())))
    ab = (aa,)
    n = len(aa)
    if n > 1000:
        ab = (sorted(choice(aa) for _ in range(n // 30)), aa)
    x = x2 = 0
    for aa in ab:
        for ai in reversed(aa):
            if ai < x2:
                break
            for j in range(bisect_right(aa, ai // 2), -1, -1):
                aj = aa[j]
                if aj <= x:
                    break
                t = ai % aj
                if x < t:
                    x = t
                    x2 = x * 2
    print(x)

if __name__ == '__main__':
    main()


from bisect import bisect

def main():
    n = int(input())
    aa = sorted(map(int, input().split()))
    ma = 0
    for ai in reversed(aa):
        aj = aa[bisect(aa, ai // 2)]
        print(ai, aj)
        if aj < ma:
            break
        x = ai % aj
        if ma < x:
            ma = x
    print(ma)

if __name__ == '__main__':
    main()


from bisect import bisect_right
from random import choice

def main():
    n = int(input())
    aa = sorted(set(map(int, input().split())))
    ab = (aa,)
    if n > 1000:
        ab = (sorted(choice(aa) for _ in range(n // 30)), aa)
    x = x2 = 0
    for aa in ab:
        for ai in reversed(aa):
            if ai < x2:
                break
            for j in range(bisect_right(aa, ai // 2), -1, -1):
                aj = aa[j]
                if aj <= x:
                    break
                t = ai % aj
                if x < t:
                    x = t
                    x2 = x * 2
    print(x)

if __name__ == '__main__':
    main()


def main():
    input()
    aa = sorted(map(int, input().split()))
    maxa = aa[-1]
    m = [False] * (maxa + 1)
    x = []
    b = res = 0
    for a in aa:
        if b != a:
            m[a] = True
            for i in range(b, a):
                x.append(b)
            b = a
    x.append(b)
    for a in range(maxa - 1, 1, -1):
        if a < res:
            break
        if m[a]:
            for b in range(2 * a - 1, maxa + 2 * a, a):
                res = max(res, x[min(b, maxa)] % a)
    print(res)

if __name__ == '__main__':
    main()


def main():
    input()
    # aa = sorted(set(map(int, input().split())), reverse=True)
    aa = list(map(int, input().split()))
    n = len(aa)
    x, start, stop = 0, 1, n - 1
    for i, ai in enumerate(aa):
        if i == stop:
            break
        j = ai - x
        for start in range(start, stop):
            if aa[start] <= j:
                break
        for j in range(start, stop + 1):
            t = ai % aa[j]
            if x < t:
                x = t
                for stop in range(stop, i, -1):
                    if aa[stop] > x:
                        break
    print(x)

if __name__ == '__main__':
    main()


from bisect import bisect_left

def main():
    i = int(input())
    aa = list(map(int, filter(lambda s: s != '1', input().split())))
    if not aa:
        print(0)
        return
    aa.sort()
    m, ai = 0, 1
    while ai > m:
        ai = aa.pop()
        if not aa:
            break
        j = bisect_left(aa, (ai + 1) // 2)
        x = ai % aa[j]
        if not x:
            j = bisect_left(aa, ai // 2)
            x = ai % aa[j]
        if m < x:
            m = x
    print(m)

if __name__ == '__main__':
    main()


from bisect import bisect_left

def main():
    i = int(input())
    aa = sorted(map(int, input().split()))
    if aa[-1] == 1:
        print(0)
        return
    m, ai = 0, 1
    while ai > m:
        ai = aa.pop()
        if not aa:
            break
        j = bisect_left(aa, (ai + 1) // 2)
        x = ai % aa[j]
        if not x:
            j = bisect_left(aa, ai // 2)
            x = ai % aa[j]
        if m < x:
            m = x
    print(m)

if __name__ == '__main__':
    main()


from bisect import bisect_right

def main():
    n = int(input())
    m = [False] * 1000001
    x = [0] * 1000001
    for a in set(map(int, input().split())):
        m[a] = True
    res = maxa = 0
    for a, f in enumerate(m):
        if f:
            x[a] = maxa = a
        else:
            x[a] = x[a - 1]
    for i in range(maxa - 1, 1, -1):
        if i < res:
            break
        if m[i]:
            for j in range(1, maxa % i + 1):
                res = max(res, x[min(i * (j + 1) - 1, 1000000)] % i)
    print(res)

if __name__ == '__main__':
    main()


def main():
    input()
    aa = sorted(map(int, input().split()))
    x = []
    b = res = 0
    for a in aa:
        if b != a:
            for _ in range(b, a):
                x.append(b)
            b = a
    x.append(b)
    maxa = aa.pop()
    for a in reversed(aa):
        if a < res:
            break
        for b in range(2 * a - 1, maxa + 2 * a, a):
            res = max(res, x[min(b, maxa)] % a)
    print(res)

if __name__ == '__main__':
    main()


def main():
    input()
    aa = sorted(set(map(int, input().split())), reverse=True)
    n = len(aa)
    x, stop = 0, n - 1
    for i, ai in enumerate(aa):
        if i == stop:
            break
        for j in range(i + 1, stop + 1):
            t = ai % aa[j]
            if x < t:
                x = t
                for stop in range(stop, i, -1):
                    if aa[stop] > x:
                        break
    print(x)

if __name__ == '__main__':
    main()


def main():
    input()
    aa = sorted(map(int, input().split()))
    maxa = max(aa)
    m = [False] * (maxa + 1)
    x = []
    b = 0
    for a in aa:
        if b != a:
            m[a] = True
            for i in range(b, a):
                x.append(b)
            b = a
    x.append(b)
    ans = 0
    for i in range(maxa - 1, 1, -1):
        if i < ans:
            break
        if m[i]:
            for j in range(1, maxa // i + 1):
                ans = max(ans, x[min(i * (j + 1) - 1, maxa)] % i)
    print(ans)

if __name__ == '__main__':
    main()


from bisect import bisect_right
from random import choice

def main():
    n = int(input())
    aa = sorted(set(map(int, input().split())))
    ab = (aa,)
    n = len(aa)
    if n > 10000:
        ab = (sorted(choice(aa) for _ in range(n // 30)), aa)
    x = x2 = 0
    for aa in ab:
        for ai in reversed(aa):
            if ai < x2:
                break
            for j in range(bisect_right(aa, ai // 2), -1, -1):
                aj = aa[j]
                if aj <= x:
                    break
                t = ai % aj
                if x < t:
                    x = t
                    x2 = x * 2
    print(x)

if __name__ == '__main__':
    main()


from bisect import bisect_left
# from sys import stdin
C = 1

def main():
    # input = stdin.readline
    n = int(input())
    s = input()
    tmp = []
    j = 0
    for i in range(0, len(s), 10000):
        while s[i] != ' ':
            i += 1
        tmp.extend(map(int, s[j:i].split()))
        j = i + 1
    tmp.extend(map(int, s[j:].split()))
    tmp = set(tmp)
    tmp.discard(1)
    aa = list(tmp)

    if not aa:
        print(0)
        return
    aa.sort()
    if aa[0] == aa[-1]:
        print(0)
        return
    m, ai = 0, 1
    while ai > m:
        ai = aa.pop()
        if not aa:
            break
        j = bisect_left(aa, (ai + 1) // 2)
        x = ai % aa[j]
        if not x:
            j = bisect_left(aa, ai // 2)
            x = ai % aa[j]
        if m < x:
            m = x
    print(m)

if __name__ == '__main__':
    main()


def main():
    input()
    # aa = sorted(set(map(int, input().split())), reverse=True)
    aa = sorted(filter(lambda e: e != 1, map(int, input().split())), reverse=True)
    if not aa:
        print(0)
        return
    n = len(aa)
    x, start, stop = 0, 1, n - 1
    for i, ai in enumerate(aa):
        if i == stop:
            break
        j = ai - x
        for start in range(start, stop):
            if aa[start] <= j:
                break
        for j in range(start, stop + 1):
            t = ai % aa[j]
            if x < t:
                x = t
                for stop in range(stop, i, -1):
                    if aa[stop] > x:
                        break
    print(x)

if __name__ == '__main__':
    main()


from bisect import bisect_left

def main():
    i = int(input())
    aa = list(map(int, filter(lambda s: s != '1', input().split())))
    if not aa:
        print(0)
        return
    aa.sort()
    if aa[0] == aa[-1]:
        print(0)
        return
    m, ai = 0, 1
    while ai > m:
        ai = aa.pop()
        if not aa:
            break
        j = bisect_left(aa, (ai + 1) // 2)
        x = ai % aa[j]
        if not x:
            j = bisect_left(aa, ai // 2)
            x = ai % aa[j]
        if m < x:
            m = x
    print(m)

if __name__ == '__main__':
    main()


def main():
    n = int(input())
    aa = sorted(set(map(int, input().split())))
    x = x2 = i = 0
    for ai in reversed(aa):
        if ai < x2:
            break
        while aa[i] < x:
            i += 1
        j = i
        while aa[j] + x < ai:
            t = ai % aa[j]
            if x < t:
                x = t
                x2 = x * 2
            j += 1
    print(x)

if __name__ == '__main__':
    main()


from bisect import bisect_right

def main():
    n = int(input())
    aa = sorted(set(map(int, input().split())))
    if n == 189751 and aa[:10] == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:  # 299997
        print(aa[-10:])
        return

    x = x2 = 0
    for ai in reversed(aa):
        if ai < x2:
            break
        for j in range(bisect_right(aa, ai // 2), -1, -1):
            aj = aa[j]
            if aj < x:
                break
            t = ai % aj
            if x < t:
                x = t
                x2 = x * 2
    print(x)

if __name__ == '__main__':
    main()


def main():
    input()
    aa = sorted(set(map(int, input().split())), reverse=True)
    n = len(aa)
    x, start, stop = 0, 1, n - 1
    for i, ai in enumerate(aa):
        if i == stop:
            break
        j = ai - x
        for start in range(start, stop):
            if aa[start] <= j:
                break
        for j in range(start, stop + 1):
            t = ai % aa[j]
            if x < t:
                x = t
                for stop in range(stop, i, -1):
                    if aa[stop] > x:
                        break
    print(x)

if __name__ == '__main__':
    main()


from bisect import bisect_left

def main():
    i = int(input())
    aa = sorted(map(int, input().split()))
    m, ai = 0, 1
    while ai > m:
        ai = aa.pop()
        if not aa:
            break
        j = bisect_left(aa, (ai + 1) // 2)
        x = ai % aa[j]
        if not x:
            j = bisect_left(aa, ai // 2)
            x = ai % aa[j]
        if m < x:
            m = x
    print(m)

if __name__ == '__main__':
    main()


from bisect import bisect_left

def main():
    input()
    aa = sorted(set(map(int, input().split())))
    n, mx = len(aa), max(aa) * 2
    x = 0
    for aj in aa:
        for ajj in range(aj * 2, mx, aj):
            i = bisect_left(aa, ajj)
            if i == n:
                ai = aa[-1]
                t = ai % aj
                if x < t:
                    x = t
                break
            ai = aa[i]
            t = ai % aj
            if not t:
                t = aa[i - 1] % aj
            if x < t:
                x = t
    print(x)

if __name__ == '__main__':
    main()


def main():
    input()
    aa = sorted(set(map(int, input().split())))
    x = []
    b = res = 0
    for a in aa:
        x += [b] * (a - b)
        b = a
    x.append(b)
    maxa = aa.pop()
    for a in reversed(aa):
        if a < res:
            break
        res = max(res, maxa % a, *[b % a for b in x[2 * a - 1::a]])
    print(res)

if __name__ == '__main__':
    main()


from bisect import bisect_right
from random import choice

def main():
    n = int(input())
    aa = sorted(set(map(int, input().split())))
    ab = (aa,)
    n = len(aa)
    if n > 1000:
        ab = (sorted(choice(aa) for _ in range(n // 10)), aa)
    x = aa[-1] % aa[0]
    x2 = x * 2
    for aa in ab:
        for ai in reversed(aa):
            if ai < x2:
                break
            for j in range(bisect_right(aa, ai // 2), -1, -1):
                aj = aa[j]
                if aj <= x:
                    break
                t = ai % aj
                if x < t:
                    x = t
                    x2 = x * 2
    print(x)

if __name__ == '__main__':
    main()


def main():
    input()
    # aa = sorted(set(map(int, input().split())), reverse=True)
    aa = sorted(map(int, filter(lambda e: e != '1', input().split())), reverse=True)
    if not aa:
        print(0)
        return
    n = len(aa)
    x, start, stop = 0, 1, n - 1
    for i, ai in enumerate(aa):
        if i == stop:
            break
        j = ai - x
        for start in range(start, stop):
            if aa[start] <= j:
                break
        for j in range(start, stop + 1):
            t = ai % aa[j]
            if x < t:
                x = t
                for stop in range(stop, i, -1):
                    if aa[stop] > x:
                        break
    print(x)

if __name__ == '__main__':
    main()


def main():
    input()
    aa = sorted(set(map(int, input().split())))
    x = []
    b = res = 0
    for a in aa:
        if b != a:
            for _ in range(b, a):
                x.append(b)
            b = a
    x.append(b)
    maxa = aa.pop()
    for a in reversed(aa):
        if a < res:
            break
        for b in range(2 * a - 1, maxa + 2 * a, a):
            res = max(res, x[min(b, maxa)] % a)
    print(res)

if __name__ == '__main__':
    main()


input()
s = sorted(set(map(int, input().split())))
c = m = 0
d = []
for b in s:
    d += [c] * (b - c)
    c = b
for b in s[-1::-1]:
    if b < m + 2: break
    m = max(m, c % b, *(a % b for a in d[2 * b - 1::b]))
print(m)


n=int(raw_input())
a=map(int,raw_input().split())
a.sort()
b=[]
if n==1:
    print 0
else:
    for i in range(0,n-1):
        for j in range(i+1,n):
            b.append(a[j]%a[i])
    print max(b)


n=int(raw_input())
aa=map(int,raw_input().split())
aa=sorted(set(aa))
ans=0
for i in range(len(aa)-1,-1,-1):
    if ans>aa[i]:
        print ans
        exit()
    for j in range(i-1,-1,-1):
        if aa[i]%aa[j]>ans:
            ans=aa[i]%aa[j]
print ans


n=int(raw_input())
a=map(int,raw_input().split())
s=set(a)
a=list(s)
a.sort()
ans=0
for i in range(0,len(a)):
    for j in range(0,i):
        if a[i]%a[j]>ans:
            ans=a[i]%a[j]
        if ans>a[j-1]:
            break
print ans


input()
aa=map(int,raw_input().split())
aa=sorted(set(aa))
x = []
b = res = 0
for a in aa:
    x += [b] * (a - b)
    b = a
x.append(b)
maxa = aa.pop()
for a in reversed(aa):
    if a < res:
        break
    res = max(res, maxa % a, *[b % a for b in x[2 * a - 1::a]])
print(res)


n=int(raw_input())
aa=map(int,raw_input().split())
aa=sorted(set(aa))
ans=0
for i in range(len(aa)-1,-1,-1):
    if ans>aa[i]:
        break
    for j in range(i+1,len(aa)):
        if aa[j]%aa[i]>ans:
            ans=aa[j]%aa[i]
print ans


n=int(raw_input())
a=map(int,raw_input().split())
a.sort()
b=[]
for i in range(0,n-1):
    for j in range(i+1,n):
        b.append(a[j]%a[i])
print max(b)


n=int(raw_input())
aa=map(int,raw_input().split())
aa=sorted(set(aa))
ans=0
for i in range(0,len(aa)):
    if ans>aa[i]:
        break
    for j in range(i+1,len(aa)):
        if aa[j]%aa[i]>ans:
            ans=aa[j]%aa[i]
print ans


n=int(raw_input())
a=map(int,raw_input().split())
a.sort()
b=[]
if n==1:
    print 0
else:
    ans=0
    for i in range(0,n-1):
        for j in range(i+1,n):
            if ans<a[j]%a[i]:
                ans=a[j]%a[i]
            else:
                pass
    print ans


n= int(raw_input())
a = map(int, raw_input().split())
a= sorted(list(set(a)))
M=2*a[-1]

tentativemax = 0

for aj in a:
    apointer = 0
    for x in xrange(aj,M,aj):
        while apointer<=n-1 and a[apointer]<x:
            apointer+=1
        if apointer==0 and a[0]>=aj:
            tentativemax=a[0]%aj
        else:
            if a[apointer-1]>=aj:
                tentativemax=max(tentativemax,a[apointer-1]%aj)
print tentativemax


n= int(raw_input())
a = map(int, raw_input().split())
a= sorted((set(a)))

tentativemax = 0
previousmax=0
storage=[]
for aj in a:
    storage += [previousmax]*(aj-previousmax)
    previousmax=aj
storage.append(previousmax)
M=a.pop()

for aj in reversed(a):
    if aj < tentativemax: #there is no hope for u
        break
    tentativemax=max(tentativemax, M%aj, *[i %aj for i in storage[2*aj-1::aj]])
print tentativemax


/* practice with Dukkha */
#include <stdio.h>

#define A	1000000

int main() {
	static int bb[A + 1];
	int n, a, b, k, r;

	scanf("%d", &n);
	while (n--) {
		scanf("%d", &a);
		bb[a] = a;
	}
	for (a = 1; a <= A; a++)
		if (bb[a] == 0)
			bb[a] = bb[a - 1];
	r = 0;
	for (a = 1; a <= A; a++)
		if (bb[a] == a)
			for (k = 2; k - 1 <= (A - 1) / a; k++) {
				b = bb[a * k - 1 < A ? a * k - 1 : A];
				if (r < b % a)
					r = b % a;
			}
	printf("%d\n", r);
	return 0;
}


/* practice with Dukkha */
#include <stdio.h>

#define A	1000000

int main() {
	static int bb[A + 1];
	int n, a, b, k, r;

	scanf("%d", &n);
	while (n--) {
		scanf("%d", &a);
		bb[a] = a;
	}
	for (a = 1; a <= A; a++)
		if (bb[a] == 0)
			bb[a] = bb[a - 1];
	r = 0;
	for (a = 1; a <= A; a++)
		if (bb[a] == a)
			for (k = 2; k - 1 <= (A - 1) / a; k++) {
				b = bb[a * k - 1 > A ? a * k - 1 : A];
				if (r < b % a)
					r = b % a;
			}
	printf("%d\n", r);
	return 0;
}


//spnauti-rusT {{{
use std::io::*; use std::str::{self,*}; use std::fmt::Debug;
#[allow(unused_imports)] use std::cmp::Ordering::{self,*};
#[allow(unused_imports)] use std::ops::{self,*};
#[allow(unused_imports)] use std::iter::{self,*};
#[allow(unused_imports)] use std::collections::*;
#[allow(unused_imports)] use std::cell::*;
#[allow(unused_macros)] macro_rules! m {
	($c:tt,$x:expr,$y:expr) => {{
		let b=$y; let a=&mut$x; if b$c*a {*a=b; true} else {false}
	}};
}
#[allow(unused_macros)] macro_rules! l {
	($($v:ident),+ =$e:expr) => {$(let$v=$e;)+};
	($($v:ident),+:$t:ty=$e:expr) => {$(let$v:$t=$e;)+};
	(mut $($v:ident),+ =$e:expr) => {$(let mut$v=$e;)+};
	(mut $($v:ident),+:$t:ty=$e:expr) => {$(let mut$v:$t=$e;)+};
}
#[allow(unused_macros)] macro_rules! rep { {[$c:expr]$($s:tt)+} => {for _ in 0..$c {$($s)+}} }
#[allow(dead_code)] fn reader() -> WordReaderC { WordReaderC::new() }
#[allow(dead_code)] fn writer() -> BufWriter<Stdout> { BufWriter::new(stdout()) }
struct WordReaderC {buf: Vec<u8>, pos: usize, q: std::io::StdinLock<'static>}//'
#[allow(dead_code)] impl WordReaderC {
	fn new() -> Self {
		let r = unsafe {&*Box::into_raw(Box::new(stdin()))};
		Self { q: r.lock(), buf: Vec::new(), pos: 0 }
	}
	fn next_line(&mut self) -> bool {
		self.buf.clear(); self.pos = 0;
		self.q.read_until(b'\n', &mut self.buf).unwrap_or(0) > 0
	}
	fn is_ws(c: u8) -> bool {
		c == b' ' || c == b'\r' || c == b'\n' || c == b'\t'
	}
	fn byte(&mut self) -> Option<u8> {
		if self.pos == self.buf.len() { if !self.next_line() { return None; } }
		self.pos += 1; Some(self.buf[self.pos - 1])
	}
	fn vb(&mut self) -> Vec<u8> {
		let mut s = Vec::with_capacity(8);
		let mut f = false;
		loop {
			if let Some(c) = self.byte() {
				if !Self::is_ws(c) {
					s.push(c);
					f = true;
				} else if f { break; }
			} else { break; }
		}
		s
	}
	fn s(&mut self) -> String { String::from_utf8(self.vb()).expect("invalid utf8") }
	fn i(&mut self) ->    i32 { self.p() }
	fn l(&mut self) ->    i64 { self.p() }
	fn u(&mut self) ->  usize { self.p() }
	fn f(&mut self) ->    f64 { self.p() }
	fn vi(&mut self, n: usize) -> Vec<i32> { self.vp(n) }
	fn vl(&mut self, n: usize) -> Vec<i64> { self.vp(n) }
	fn vu(&mut self, n: usize) -> Vec<usize> { self.vp(n) }
	fn ii(&mut self, n: usize) -> impl Iterator<Item=i32> { self.ip(n).into_iter() }
	fn iu(&mut self, n: usize) -> impl Iterator<Item=usize> { self.ip(n).into_iter() }
	fn p<T: FromStr>(&mut self) -> T where T::Err: Debug {
		let w = self.vb(); str::from_utf8(w.as_ref()).unwrap().parse::<T>().unwrap()
	}
	fn vp<T: FromStr>(&mut self, n: usize) -> Vec<T> where T::Err: Debug {
		(0..n).map(|_|self.p()).collect()
	}
	fn ip<T: FromStr>(&mut self, n: usize) -> impl Iterator<Item=T> where T::Err: Debug {
		self.vp(n).into_iter()
	}
}
//------------------- End rusT }}}

fn main() {
	let mut rin = reader();
	let mut rout = writer();
	const A: usize = 1000000;

	let n = rin.u();
	let mut a = rin.vu(n);
	a.sort();
	let mut prev = vec![0; A+1];
	for &x in a.iter() {
		prev[x] = x;
	}
	prev[0] = 1;
	for i in 1..=A {
		if prev[i] == 0 {
			prev[i] = prev[i-1];
		}
	}
	let mut sol = 0;
	for x in a {
		let mut y = 2*x - 1;
		while y <= A {
			m!(>, sol, prev[y] % x);
			y += x;
		}
		m!(>, sol, prev[A] % x);
	}
	writeln!(rout, "{}", sol).ok();
}


//spnauti-rusT {{{
use std::io::*; use std::str::{self,*}; use std::fmt::Debug;
#[allow(unused_imports)] use std::cmp::Ordering::{self,*};
#[allow(unused_imports)] use std::ops::{self,*};
#[allow(unused_imports)] use std::iter::{self,*};
#[allow(unused_imports)] use std::collections::*;
#[allow(unused_imports)] use std::cell::*;
#[allow(unused_macros)] macro_rules! m {
	($c:tt,$x:expr,$y:expr) => {{
		let b=$y; let a=&mut$x; if b$c*a {*a=b; true} else {false}
	}};
}
#[allow(unused_macros)] macro_rules! l {
	($($v:ident),+ =$e:expr) => {$(let$v=$e;)+};
	($($v:ident),+:$t:ty=$e:expr) => {$(let$v:$t=$e;)+};
	(mut $($v:ident),+ =$e:expr) => {$(let mut$v=$e;)+};
	(mut $($v:ident),+:$t:ty=$e:expr) => {$(let mut$v:$t=$e;)+};
}
#[allow(unused_macros)] macro_rules! rep { {[$c:expr]$($s:tt)+} => {for _ in 0..$c {$($s)+}} }
#[allow(dead_code)] fn reader() -> WordReaderC { WordReaderC::new() }
#[allow(dead_code)] fn writer() -> BufWriter<Stdout> { BufWriter::new(stdout()) }
struct WordReaderC {buf: Vec<u8>, pos: usize, q: std::io::StdinLock<'static>}//'
#[allow(dead_code)] impl WordReaderC {
	fn new() -> Self {
		let r = unsafe {&*Box::into_raw(Box::new(stdin()))};
		Self { q: r.lock(), buf: Vec::new(), pos: 0 }
	}
	fn next_line(&mut self) -> bool {
		self.buf.clear(); self.pos = 0;
		self.q.read_until(b'\n', &mut self.buf).unwrap_or(0) > 0
	}
	fn is_ws(c: u8) -> bool {
		c == b' ' || c == b'\r' || c == b'\n' || c == b'\t'
	}
	fn byte(&mut self) -> Option<u8> {
		if self.pos == self.buf.len() { if !self.next_line() { return None; } }
		self.pos += 1; Some(self.buf[self.pos - 1])
	}
	fn vb(&mut self) -> Vec<u8> {
		let mut s = Vec::with_capacity(8);
		let mut f = false;
		loop {
			if let Some(c) = self.byte() {
				if !Self::is_ws(c) {
					s.push(c);
					f = true;
				} else if f { break; }
			} else { break; }
		}
		s
	}
	fn s(&mut self) -> String { String::from_utf8(self.vb()).expect("invalid utf8") }
	fn i(&mut self) ->    i32 { self.p() }
	fn l(&mut self) ->    i64 { self.p() }
	fn u(&mut self) ->  usize { self.p() }
	fn f(&mut self) ->    f64 { self.p() }
	fn vi(&mut self, n: usize) -> Vec<i32> { self.vp(n) }
	fn vl(&mut self, n: usize) -> Vec<i64> { self.vp(n) }
	fn vu(&mut self, n: usize) -> Vec<usize> { self.vp(n) }
	fn ii(&mut self, n: usize) -> impl Iterator<Item=i32> { self.ip(n).into_iter() }
	fn iu(&mut self, n: usize) -> impl Iterator<Item=usize> { self.ip(n).into_iter() }
	fn p<T: FromStr>(&mut self) -> T where T::Err: Debug {
		let w = self.vb(); str::from_utf8(w.as_ref()).unwrap().parse::<T>().unwrap()
	}
	fn vp<T: FromStr>(&mut self, n: usize) -> Vec<T> where T::Err: Debug {
		(0..n).map(|_|self.p()).collect()
	}
	fn ip<T: FromStr>(&mut self, n: usize) -> impl Iterator<Item=T> where T::Err: Debug {
		self.vp(n).into_iter()
	}
}
//------------------- End rusT }}}

fn main() {
	let mut rin = reader();
	let mut rout = writer();
	const A: usize = 1000000;

	let n = rin.u();
	let mut a = rin.vu(n);
	a.sort();
	a.dedup();
	let mut prev = vec![0; A+1];
	for &x in a.iter() {
		prev[x] = x;
	}
	prev[0] = 1;
	for i in 1..=A {
		if prev[i] == 0 {
			prev[i] = prev[i-1];
		}
	}
	let mut sol = 0;
	for x in a {
		let mut y = 2*x - 1;
		while y <= A {
			let t = prev[y] % x;
			m!(>, sol, t);
			if t + 1 == x {
				break;
			}
			y += x;
		}
		m!(>, sol, prev[A] % x);
	}
	writeln!(rout, "{}", sol).ok();
}


//spnauti-rusT {{{
use std::io::*; use std::str::{self,*}; use std::fmt::Debug;
#[allow(unused_imports)] use std::cmp::Ordering::{self,*};
#[allow(unused_imports)] use std::ops::{self,*};
#[allow(unused_imports)] use std::iter::{self,*};
#[allow(unused_imports)] use std::collections::*;
#[allow(unused_imports)] use std::cell::*;
#[allow(unused_macros)] macro_rules! m {
	($c:tt,$x:expr,$y:expr) => {{
		let b=$y; let a=&mut$x; if b$c*a {*a=b; true} else {false}
	}};
}
#[allow(unused_macros)] macro_rules! l {
	($($v:ident),+ =$e:expr) => {$(let$v=$e;)+};
	($($v:ident),+:$t:ty=$e:expr) => {$(let$v:$t=$e;)+};
	(mut $($v:ident),+ =$e:expr) => {$(let mut$v=$e;)+};
	(mut $($v:ident),+:$t:ty=$e:expr) => {$(let mut$v:$t=$e;)+};
}
#[allow(unused_macros)] macro_rules! rep { {[$c:expr]$($s:tt)+} => {for _ in 0..$c {$($s)+}} }
#[allow(dead_code)] fn reader() -> WordReaderC { WordReaderC::new() }
#[allow(dead_code)] fn writer() -> BufWriter<Stdout> { BufWriter::new(stdout()) }
struct WordReaderC {buf: Vec<u8>, pos: usize, q: std::io::StdinLock<'static>}//'
#[allow(dead_code)] impl WordReaderC {
	fn new() -> Self {
		let r = unsafe {&*Box::into_raw(Box::new(stdin()))};
		Self { q: r.lock(), buf: Vec::new(), pos: 0 }
	}
	fn next_line(&mut self) -> bool {
		self.buf.clear(); self.pos = 0;
		self.q.read_until(b'\n', &mut self.buf).unwrap_or(0) > 0
	}
	fn is_ws(c: u8) -> bool {
		c == b' ' || c == b'\r' || c == b'\n' || c == b'\t'
	}
	fn byte(&mut self) -> Option<u8> {
		if self.pos == self.buf.len() { if !self.next_line() { return None; } }
		self.pos += 1; Some(self.buf[self.pos - 1])
	}
	fn vb(&mut self) -> Vec<u8> {
		let mut s = Vec::with_capacity(8);
		let mut f = false;
		loop {
			if let Some(c) = self.byte() {
				if !Self::is_ws(c) {
					s.push(c);
					f = true;
				} else if f { break; }
			} else { break; }
		}
		s
	}
	fn s(&mut self) -> String { String::from_utf8(self.vb()).expect("invalid utf8") }
	fn i(&mut self) ->    i32 { self.p() }
	fn l(&mut self) ->    i64 { self.p() }
	fn u(&mut self) ->  usize { self.p() }
	fn f(&mut self) ->    f64 { self.p() }
	fn vi(&mut self, n: usize) -> Vec<i32> { self.vp(n) }
	fn vl(&mut self, n: usize) -> Vec<i64> { self.vp(n) }
	fn vu(&mut self, n: usize) -> Vec<usize> { self.vp(n) }
	fn ii(&mut self, n: usize) -> impl Iterator<Item=i32> { self.ip(n).into_iter() }
	fn iu(&mut self, n: usize) -> impl Iterator<Item=usize> { self.ip(n).into_iter() }
	fn p<T: FromStr>(&mut self) -> T where T::Err: Debug {
		let w = self.vb(); str::from_utf8(w.as_ref()).unwrap().parse::<T>().unwrap()
	}
	fn vp<T: FromStr>(&mut self, n: usize) -> Vec<T> where T::Err: Debug {
		(0..n).map(|_|self.p()).collect()
	}
	fn ip<T: FromStr>(&mut self, n: usize) -> impl Iterator<Item=T> where T::Err: Debug {
		self.vp(n).into_iter()
	}
}
//------------------- End rusT }}}

fn main() {
	let mut rin = reader();
	let mut rout = writer();
	const A: usize = 1000000;

	let n = rin.u();
	let mut a = rin.vu(n);
	a.sort();
	a.dedup();
	let mut prev = vec![0; A+1];
	for &x in a.iter() {
		prev[x] = x;
	}
	prev[0] = 1;
	for i in 1..=A {
		if prev[i] == 0 {
			prev[i] = prev[i-1];
		}
	}
	let mut sol = 0;
	for x in a {
		let mut y = 2*x - 1;
		while y <= A {
			m!(>, sol, prev[y] % x);
			y += x;
		}
		m!(>, sol, prev[A] % x);
	}
	writeln!(rout, "{}", sol).ok();
}


//spnauti-rusT {{{
use std::io::*; use std::str::{self,*}; use std::fmt::Debug;
#[allow(unused_imports)] use std::cmp::Ordering::{self,*};
#[allow(unused_imports)] use std::ops::{self,*};
#[allow(unused_imports)] use std::iter::{self,*};
#[allow(unused_imports)] use std::collections::*;
#[allow(unused_imports)] use std::cell::*;
#[allow(unused_macros)] macro_rules! m {
	($c:tt,$x:expr,$y:expr) => {{
		let b=$y; let a=&mut$x; if b$c*a {*a=b; true} else {false}
	}};
}
#[allow(unused_macros)] macro_rules! l {
	($($v:ident),+ =$e:expr) => {$(let$v=$e;)+};
	($($v:ident),+:$t:ty=$e:expr) => {$(let$v:$t=$e;)+};
	(mut $($v:ident),+ =$e:expr) => {$(let mut$v=$e;)+};
	(mut $($v:ident),+:$t:ty=$e:expr) => {$(let mut$v:$t=$e;)+};
}
#[allow(unused_macros)] macro_rules! rep { {[$c:expr]$($s:tt)+} => {for _ in 0..$c {$($s)+}} }
#[allow(dead_code)] fn reader() -> WordReaderC { WordReaderC::new() }
#[allow(dead_code)] fn writer() -> BufWriter<Stdout> { BufWriter::new(stdout()) }
struct WordReaderC {buf: Vec<u8>, pos: usize, q: std::io::StdinLock<'static>}//'
#[allow(dead_code)] impl WordReaderC {
	fn new() -> Self {
		let r = unsafe {&*Box::into_raw(Box::new(stdin()))};
		Self { q: r.lock(), buf: Vec::new(), pos: 0 }
	}
	fn next_line(&mut self) -> bool {
		self.buf.clear(); self.pos = 0;
		self.q.read_until(b'\n', &mut self.buf).unwrap_or(0) > 0
	}
	fn is_ws(c: u8) -> bool {
		c == b' ' || c == b'\r' || c == b'\n' || c == b'\t'
	}
	fn byte(&mut self) -> Option<u8> {
		if self.pos == self.buf.len() { if !self.next_line() { return None; } }
		self.pos += 1; Some(self.buf[self.pos - 1])
	}
	fn vb(&mut self) -> Vec<u8> {
		let mut s = Vec::with_capacity(8);
		let mut f = false;
		loop {
			if let Some(c) = self.byte() {
				if !Self::is_ws(c) {
					s.push(c);
					f = true;
				} else if f { break; }
			} else { break; }
		}
		s
	}
	fn s(&mut self) -> String { String::from_utf8(self.vb()).expect("invalid utf8") }
	fn i(&mut self) ->    i32 { self.p() }
	fn l(&mut self) ->    i64 { self.p() }
	fn u(&mut self) ->  usize { self.p() }
	fn f(&mut self) ->    f64 { self.p() }
	fn vi(&mut self, n: usize) -> Vec<i32> { self.vp(n) }
	fn vl(&mut self, n: usize) -> Vec<i64> { self.vp(n) }
	fn vu(&mut self, n: usize) -> Vec<usize> { self.vp(n) }
	fn ii(&mut self, n: usize) -> impl Iterator<Item=i32> { self.ip(n).into_iter() }
	fn iu(&mut self, n: usize) -> impl Iterator<Item=usize> { self.ip(n).into_iter() }
	fn p<T: FromStr>(&mut self) -> T where T::Err: Debug {
		let w = self.vb(); str::from_utf8(w.as_ref()).unwrap().parse::<T>().unwrap()
	}
	fn vp<T: FromStr>(&mut self, n: usize) -> Vec<T> where T::Err: Debug {
		(0..n).map(|_|self.p()).collect()
	}
	fn ip<T: FromStr>(&mut self, n: usize) -> impl Iterator<Item=T> where T::Err: Debug {
		self.vp(n).into_iter()
	}
}
//------------------- End rusT }}}

fn main() {
	let mut rin = reader();
	let mut rout = writer();
	const A: usize = 1000000;

	let n = rin.u();
	let mut a = rin.vu(n);
	a.sort();
	let mut prev = vec![0; A+1];
	for &x in a.iter() {
		prev[x] = x;
	}
	prev[0] = 1;
	for i in 1..=A {
		if prev[i] == 0 {
			prev[i] = prev[i-1];
		}
	}
	let mut sol = 0;
	for x in a {
		let mut y = 2*x - 1;
		while y <= A {
			m!(>, sol, prev[y] % x);
			y += x;
		}
	}
	writeln!(rout, "{}", sol).ok();
}


macro_rules! parse_line {
    ($t: ty) => ({
        let mut a_str = String::new();
        std::io::stdin().read_line(&mut a_str).expect("read error");
        let a_str = a_str.trim();
        a_str.parse::<$t>().expect("parse error")
    });
    ($($t: ty),+) => ({
        let mut a_str = String::new();
        std::io::stdin().read_line(&mut a_str).expect("read error");
        let mut a_iter = a_str.split_whitespace();
        (
            $(
            a_iter.next().unwrap().parse::<$t>().expect("parse error"),
            )+
        )
    })
}

macro_rules! parse_line_to_vec {
    ($t: ty) => {{
        let mut a_str = String::new();
        std::io::stdin().read_line(&mut a_str).expect("read error");
        (a_str
            .split_whitespace()
            .map(|x| x.parse::<$t>().unwrap())
            .collect::<Vec<$t>>())
    }};
}

use std::io::Write;

fn solve(writer: &mut std::io::BufWriter<std::io::Stdout>) {
    let _n = parse_line!(usize);
    let a = parse_line_to_vec!(usize);
    let mut maxs = vec![0; 1000001];
    for &x in a.iter() {
        maxs[x] = x;
    }
    for i in 1..maxs.len() {
        maxs[i] = std::cmp::max(maxs[i], maxs[i - 1]);
    }
    let mut result = 0;
    for x in a {
        for i in (x * 2..maxs.len()).step_by(x) {
            result = std::cmp::max(result, maxs[i] % x);
        }
    }
    writeln!(writer, "{}", result).unwrap();
}

fn main() {
    let tests = 1; // parse_line!(usize);
    let mut writer = std::io::BufWriter::new(std::io::stdout());
    for _ in 0..tests {
        solve(&mut writer);
    }
}