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

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

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

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

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

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

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

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

   try {
    FileOutputStream output=new FileOutputStream("output.txt");
    PrintStream out=new PrintStream(output);
    //Diverting the output stream into file "temp.out".Comment the below line to use console
    System.setOut(out);

    InputStream input=new FileInputStream("input.txt");
    //Diverting the input stream into file "temp.in".Comment the below line to use console
    System.setIn(input);

   } catch (FileNotFoundException e) {
    e.printStackTrace();
   }
}
 static class skill{
 	int height;
 	int index;
 	int tower;
 	skill(int height,int index){
 		this.height=height;
 		this.index=index;
 		this.tower=-1;
 	}
 }
  static class skill2{
 	int sum;
 	int tower;

 	skill2(int sum,int tower){
 		this.sum=sum;
 		this.tower=tower;
 	}
 }
 static class sort implements Comparator<skill>{
	@Override
	public int compare(skill node0,skill node1){
		return node0.height-node1.height;
	}
}
 static class sort2 implements Comparator<skill>{
	@Override
	public int compare(skill node0,skill node1){
		return node0.index-node1.index;
	}
}
 static class sort3 implements Comparator<skill2>{
	@Override
	public int compare(skill2 node0,skill2 node1){
		return node0.sum-node1.sum;
	}
}

public static void main(String args[]) throws Exception
{
//Input();
FastReader sc=new FastReader();
int t=sc.nextInt();
for (int test=1;test<=t;test++){
	int n=sc.nextInt();
	String str=sc.nextLine();
	int flag=0;
	for(int i=0;i<n-1;i++){
		if(str.charAt(i)!=str.charAt(i+1)){
			for(int j=i+1;j<n;j++){
				if(str.charAt(i)==str.charAt(j)){
					flag=1;
					break;
				}
			}
		}
	}
	if(flag==1){
		System.out.println("NO");
	}
	else{
System.out.println("YES");
	}

}
}
}

// 	XOR OR
// 11	0	1
// 10	1	1
// 01	1	1
// 00	1	0

5
3
ABA
11
DDBBCCCBBEZ
7
FFGZZZY
1
Z
2
AB

YES
YES
YES
YES
YES
YES
YES
YES
YES
YES
YES

#include <bits/stdc++.h>
#include <string>

using namespace std;

bool susp() {
    int n;
    cin >> n;
    string days;
    cin >> days;
    for (int i = 0; i < n - 1; i++) {
        for (int j = i + 1; j < n; j++) {
            if (days[j] == days[i] && days[j - 1] != days[i])
                return false;
        }
    }
    return true;
}

int main()
{
    int t;
    cin >> t;
    bool cases[t];
    for (int i = 0; i < t; i++) {
        cases[i] = susp();
    }
    for (bool b : cases) {
        if (b)
            cout << "YES" << endl;
        else
            cout << "NO" << endl;
    }
    return 0;
}


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

public class B implements Runnable {
	boolean judge = true;
	FastReader sc;
	PrintWriter out;
	String INPUT = "";

	void solve()
	{
		int n = sc.nextInt();
		String s = sc.nextLine();

		int ans = 0;
		for(int i = 25; i >= 0; i--)
		{

			outer: while(true)
			{
				int cnt = 0;
				for(int j = 1; j < s.length(); j++)
				{
					int prev = s.charAt(j-1)-'a';
					int cur = s.charAt(j)-'a';

					if(prev == i && cur == i-1)
					{
						ans++;
						s = s.substring(0,j-1)+s.substring(j);
						continue outer;
					}

					else if(prev == i-1 && cur == i)
					{
						ans++;
						s = s.substring(0,j)+s.substring(j+1);
						continue outer;
					}
				}
				break;
			}
		}

		out.println(ans);
	}

	class Node implements Comparable<Node>
	{

		int val;
		int in;

		Node(int val,int in)
		{
			this.val = val;
			this.in = in;
		}

		public int compareTo(Node o)
		{

			if(val < o.val) return 1;  //decreasing order
			else return -1;
		}
	}

	public void run() {
		long time = System.currentTimeMillis();
		boolean oj = System.getProperty("ONLINE_JUDGE") != null || judge;
		out = new PrintWriter(System.out);
		sc = new FastReader(oj);
		solve();
		out.flush();
		if (!oj) {
			System.out.println(Arrays.deepToString(new Object[] { System.currentTimeMillis() - time + " ms" }));
		}
	}

	public static void main(String[] args) {
		new Thread(null, new B(), "Main", 1 << 28).start();
	}

	class FastReader {
		InputStream is;

		public FastReader(boolean onlineJudge) {
			is = onlineJudge ? System.in : new ByteArrayInputStream(INPUT.getBytes());
		}

		byte[] inbuf = new byte[1024];
		public int lenbuf = 0, ptrbuf = 0;

		int readByte() {
			if (lenbuf == -1)
				throw new InputMismatchException();
			if (ptrbuf >= lenbuf) {
				ptrbuf = 0;
				try {
					lenbuf = is.read(inbuf);
				} catch (IOException e) {
					throw new InputMismatchException();
				}
				if (lenbuf <= 0)
					return -1;
			}
			return inbuf[ptrbuf++];
		}

		boolean isSpaceChar(int c) {
			return !(c >= 33 && c <= 126);
		}

		int skip() {
			int b;
			while ((b = readByte()) != -1 && isSpaceChar(b))
				;
			return b;
		}

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

		char nextChar() {
			return (char) skip();
		}

		String next() {
			int b = skip();
			StringBuilder sb = new StringBuilder();
			while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ')
				sb.appendCodePoint(b);
				b = readByte();
			}
			return sb.toString();
		}

		String nextLine() {
			int b = skip();
			StringBuilder sb = new StringBuilder();
			while ((!isSpaceChar(b) || b == ' ')) { // when nextLine, (isSpaceChar(b) && b != ' ')
				sb.appendCodePoint(b);
				b = readByte();
			}
			return sb.toString();
		}

		char[] next(int n) {
			char[] buf = new char[n];
			int b = skip(), p = 0;
			while (p < n && !(isSpaceChar(b))) {
				buf[p++] = (char) b;
				b = readByte();
			}
			return n == p ? buf : Arrays.copyOf(buf, p);
		}

		int nextInt() {
			int num = 0, b;
			boolean minus = false;
			while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
				;
			if (b == '-') {
				minus = true;
				b = readByte();
			}

			while (true) {
				if (b >= '0' && b <= '9') {
					num = num * 10 + (b - '0');
				} else {
					return minus ? -num : num;
				}
				b = readByte();
			}
		}

		long nextLong() {
			long num = 0;
			int b;
			boolean minus = false;
			while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
				;
			if (b == '-') {
				minus = true;
				b = readByte();
			}

			while (true) {
				if (b >= '0' && b <= '9') {
					num = num * 10 + (b - '0');
				} else {
					return minus ? -num : num;
				}
				b = readByte();
			}
		}

		char[][] nextMatrix(int n, int m) {
			char[][] map = new char[n][];
			for (int i = 0; i < n; i++)
				map[i] = next(m);
			return map;
		}

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

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

		int[][] next2DInt(int n, int m) {
			int[][] arr = new int[n][];
			for (int i = 0; i < n; i++) {
				arr[i] = nextIntArray(m);
			}
			return arr;
		}

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

		int[] shuffle(int[] arr) {
			Random r = new Random();
			for (int i = 1, j; i < arr.length; i++) {
				j = r.nextInt(i);
				int c = arr[i];
				arr[i] = arr[j];
				arr[j] = c;
			}
			return arr;
		}

		long[] shuffle(long[] arr) {
			Random r = new Random();
			for (int i = 1, j; i < arr.length; i++) {
				j = r.nextInt(i);
				long c = arr[i];
				arr[i] = arr[j];
				arr[j] = c;
			}
			return arr;
		}

		int[] uniq(int[] arr) {
			arr = sc.shuffle(arr);
			Arrays.sort(arr);
			int[] rv = new int[arr.length];
			int pos = 0;
			rv[pos++] = arr[0];
			for (int i = 1; i < arr.length; i++) {
				if (arr[i] != arr[i - 1]) {
					rv[pos++] = arr[i];
				}
			}
			return Arrays.copyOf(rv, pos);
		}

		long[] uniq(long[] arr) {
			arr = sc.shuffle(arr);
			Arrays.sort(arr);
			long[] rv = new long[arr.length];
			int pos = 0;
			rv[pos++] = arr[0];
			for (int i = 1; i < arr.length; i++) {
				if (arr[i] != arr[i - 1]) {
					rv[pos++] = arr[i];
				}
			}
			return Arrays.copyOf(rv, pos);
		}

		int[] reverse(int[] arr) {
			int l = 0, r = arr.length - 1;
			while (l < r) {
				arr[l] = arr[l] ^ arr[r];
				arr[r] = arr[l] ^ arr[r];
				arr[l] = arr[l] ^ arr[r];
				l++;
				r--;
			}
			return arr;
		}

		long[] reverse(long[] arr) {
			int l = 0, r = arr.length - 1;
			while (l < r) {
				arr[l] = arr[l] ^ arr[r];
				arr[r] = arr[l] ^ arr[r];
				arr[l] = arr[l] ^ arr[r];
				l++;
				r--;
			}
			return arr;
		}

		int[] compress(int[] arr) {
			int n = arr.length;
			int[] rv = Arrays.copyOf(arr, n);
			rv = uniq(rv);
			for (int i = 0; i < n; i++) {
				arr[i] = Arrays.binarySearch(rv, arr[i]);
			}
			return arr;
		}

		long[] compress(long[] arr) {
			int n = arr.length;
			long[] rv = Arrays.copyOf(arr, n);
			rv = uniq(rv);
			for (int i = 0; i < n; i++) {
				arr[i] = Arrays.binarySearch(rv, arr[i]);
			}
			return arr;
		}

	}
}

#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1e5 + 10;
int n, m, k;
string s;
bool check(const string& s, int j) {
  return (j > 0 && s[j - 1] + 1 == s[j]) || (j < n - 1 && s[j + 1] + 1 == s[j]);
}
void solve() {
  for (int i = 25; i >= 0; i--) {
    for (int k = 0; k < n + 20; k++) {
      for (int j = 0; j < n; j++) {
        if (s[j] - 'a' == i && check(s, j)) {
          s.erase(s.begin() + j);
        }
      }
    }
  }
  cout << n - s.length();
}
void getData() { cin >> n >> s; }
void preprocessing() {}
int main() {
  int t = 1;
  for (int i = 1; i <= t; i++) {
    getData();
    preprocessing();
    solve();
  }
  return 0;
}


import math,itertools,fractions,heapq,collections,bisect,sys,queue,copy

sys.setrecursionlimit(10**7)
inf=10**20
mod=10**9+7
dd=[(-1,0),(0,1),(1,0),(0,-1)]
ddn=[(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
# def LF(): return [float(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def LS(): return sys.stdin.readline().split()
def S(): return input()

def main():
  n=I()
  l=LI()
  sm=sum(l)

  ansl=[1]
  ans=l[0]

  a=l[0]

  for i,x in enumerate(l[1:]):
    if a>=x*2:
      ans+=x
      ansl.append(i+2)

  if ans*2>sm:
    print(len(ansl))
    print(' '.join(str(x) for x in ansl))
  else:
    print(0)

main()
# print(main())

#include <bits/stdc++.h>
using namespace std;
vector<int> v;
int main() {
  int n;
  cin >> n;
  int s = 0;
  int a[n];
  for (int i = 0; i < n; i++) {
    cin >> a[i];
    s += a[i];
  }
  v.push_back(0);
  int sum = a[0];
  for (int i = 1; i < n; i++) {
    if (a[0] >= 2 * a[i]) {
      sum += a[i];
      v.push_back(i);
    }
    if (sum * 2 > s) break;
  }
  if (sum * 2 > s) {
    cout << v.size() << "\n";
    for (int i = 0; i < v.size(); i++) {
      cout << v[i] + 1 << " ";
    }
  } else
    cout << 0;
}


 import java.io.*;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;

//notebook#4 pg#93
public class RoughWork{

	//notebook#4 pg#93
	//O(n) time, O(1) space
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int x = sc.nextInt();
		int[] input = new int[n+1];

		for(int i=1;i<=n;i++){
			input[i] = sc.nextInt();
		}

		//Another important note-Beauty of an array is just maximum subarray sum.

		long[][][] dp = new long[n+1][2][2];

		//The following values prev_opt1, prev_opt2, prev_opt3 are all 0 because we are starting at i =1 and
		//the values for the previous options will all be 0 because no elements exits at i=0
		//largest subarray sum resulted by adding an ending element multiplied by x
		long prev_opt1=0;
		//largest subarray sum resulted by adding an ending element not multiplied by x
		long prev_opt2=0;
		long prev_opt2_with_beauty=0;
		//largest subarray sum resulted by not adding the current element. If you don't add the current element
		//(since we are only looking for subarray sum), it means that the subarray beginning is to the right of the
		//current element. That means  prev_opt3 = 0 by default for all cases. This is relevant for cases when
		//both prev_opt1 and preb_opt2 are both negative values, in that case adding an element reduces the subarray sum.
		//This variable is actually not needed but added for readability reasons
		long prev_opt3=0;

		//Opt1, opt2, opt3 are the current values for the current i. prev_opt1, prev_opt2, prev_opt3 are the values of the maximum subarray sum
		//for i-1. The reason why we have these 6 variables is because we want to reduce space complexity from O(3*n) to O(1). Why O(3*n)? Because
		//for every i value we have three options that need to be recorded. But, we don't need any values other than i-1 for calculating values of i.
		long opt1 = 0;
		long opt2 = 0;
		long opt2_with_beauty = 0;
		//This variable is actually not needed but added for readability reasons
		long opt3 = 0;

		for(int i=1;i<=n;i++) {
			//opt1 will consider the possibility that that the current element is multiplied by x.
			//If the current element is multiplied by x, it can join 3 possibilities - opt1, opt2, opt3
			dp[i][0][0] = Math.max(Math.max(dp[i-1][0][0], dp[i-1][1][0]), 0) +  x*((long) input[i]);
			//In the case of opt2,
			//In this case we take the larger of prev_opt2(where no elements have been multiplied by x before) and prev_opt3(where the previous largest sum is zero).
			dp[i][1][0] = Math.max(dp[i-1][1][0], 0) + input[i];
			dp[i][1][1] = Math.max(dp[i-1][1][1], dp[i-1][0][0])+ input[i];
			//opt3 is always set to zero.
			//prev_opt1 =opt1;
			//prev_opt2 = opt2;
			//prev_opt2_with_beauty = opt2_with_beauty;
			//prev_opt3 is always set to zero.
		}

		//long result = Math.max(Math.max(Math.max(prev_opt1,prev_opt2), prev_opt2_with_beauty), prev_opt3);
		long result = 0;

		for(int i=1;i<=n;i++) {
			result = Math.max(result, dp[i][0][0]);
			result = Math.max(result, dp[i][1][0]);
			result = Math.max(result, dp[i][1][1]);
		}

		System.out.println(result);
	}
}

#include <bits/stdc++.h>
using namespace std;
long long gcd(long long a, long long b) { return b ? gcd(b, a % b) : a; }
const long long mod = 1e9 + 7;
long long modpow(long long a, long long e) {
  if (e == 0) return 1;
  long long x = modpow(a * a % mod, e >> 1);
  return e & 1 ? x * a % mod : x;
}
int n;
long long dp[300005], a[300005], cep[300005], sag[300005], ans, mn, p[300005],
    x;
int main() {
  scanf("%d%lld", &n, &x);
  for (int i = 1; i <= n; i++) {
    scanf("%lld", &a[i]);
    p[i] = p[i - 1] + a[i];
    mn = min(mn, p[i]);
    cep[i] = p[i] - mn;
    ans = max(ans, cep[i]);
  }
  mn = 0;
  for (int i = n; i >= 1; i--) {
    p[i] = p[i + 1] + a[i];
    mn = min(mn, p[i]);
    sag[i] = p[i] - mn;
  }
  for (int i = 1; i <= n; i++) {
    dp[i] = max(dp[i - 1] + (a[i] * x), a[i] * x + cep[i - 1]);
    ans = max(ans, dp[i] + sag[i + 1]);
  }
  printf("%lld", ans);
}


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

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

    static class TaskD {
        public void solve(int testNumber, FastScanner in, PrintWriter out) {
            int n = in.nextInt(), m = in.nextInt();
            int[][] a = new int[m][];
            for (int i = 0; i < m; i++) {
                a[i] = in.nextIntArray(n);
            }

            int[] max = new int[n];
            for (int i = 0; i < n; i++) {
                max[i] = n - 1;
            }
            int[] pos1 = new int[n], pos2 = new int[n];
            for (int i = 1; i < m; i++) {
                for (int j = 0; j < n; j++) {
                    pos1[a[0][j] - 1] = j;
                    pos2[a[i][j] - 1] = j;
                }

                for (int j = 0; j < n; ) {
                    int cur = pos2[a[0][j] - 1];
                    int k = 0;
                    while (j + k < n && pos2[a[0][j + k] - 1] == cur + k) {
                        k++;
                    }
                    int last = j + k - 1;
                    for (int t = 0; t < k; t++) {
                        max[j + t] = Math.min(max[j + t], last);
                    }
                    j = last + 1;
                }
            }
            long ans = 0;
            for (int i = 0; i < n; i++) {
                ans += Math.max(0, max[i] - i + 1);
            }
            out.println(ans);
        }

    }

    static class FastScanner {
        BufferedReader br;
        StringTokenizer st;

        public FastScanner(InputStream in) {
            br = new BufferedReader(new InputStreamReader(in));
        }

        public FastScanner(String fileName) {
            try {
                br = new BufferedReader(new FileReader(fileName));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }

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

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

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

    }
}

n, m = map(int, input().split())
a = []
for i in range(m):
  a.append(list(map(int, input().split())))
b = [set([]) for i in range(n)]
for i in range(n):
  for j in range(m):
    ya = a[j][i]
    if i == n-1:
      b[ya-1].add(100000000)
    else:
      b[ya-1].add(a[j][i+1])
class UnionFind():
    def __init__(self,size):
        self.table = [-1 for _  in range(size)]

    def find(self,x):
        while self.table[x] >= 0:
            x = self.table[x]
        return x

    def union(self,x,y):
        s1 = self.find(x)
        s2 = self.find(y)
        if s1 != s2:
            if self.table[s1] != self.table[s2]:
                if self.table[s1] < self.table[s2]:
                    self.table[s2] = s1
                else:
                    self.table[s1] = s2
            else:
                self.table[s1] += -1
                self.table[s2] = s1
        return
UN = UnionFind(n)
for i in range(n):
  if len(b[i]) == 1 and list(b[i])[0] !=100000000:
    UN.union(i,list(b[i])[0]-1)
d = [0]*n
for i in range(n):
  d[UN.find(i)] += 1
ans = 0
for i in range(n):
  ans += (d[i]-1)*(d[i])//2
print(ans+n)


#include <bits/stdc++.h>
using namespace std;
int main() {
  long long int n, k, t;
  cin >> t;
  while (t--) {
    cin >> n >> k;
    if (n % 2 == 0) {
      cout << n + 2 * k << endl;
    } else {
      long long int c = 0, ans;
      for (int i = 2; i <= sqrt(n); i++) {
        if (n % i == 0) {
          ans = n + i;
          c++;
          break;
        }
      }
      if (c == 0) {
        k = k - 1;
        if (k == 0) {
          cout << 2 * n << endl;
        } else {
          cout << n + n + 2 * k << endl;
        }
      } else {
        ans += 2 * (k - 1);
        cout << ans << endl;
      }
    }
  }
}

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

public class Problem
{
	public static void main (String[] args) throws java.lang.Exception
	{
		Scanner sc=new Scanner(System.in);
		int t=sc.nextInt();
		while(t-->0){
		    int n=sc.nextInt();
		    int k=sc.nextInt();
		    int a=2;
		        while(a<=n){
		            if(n%a==0){
		                n=n+a;
		                break;
		            }
		            a++;
		        }
		        n=n+(k-1)*2;
		    System.out.println(n);
		}
	}
}


n,p=map(int,input().split())
#print("{0:b}".format(n).count('1'))
t=0
while (("{0:b}".format(n).count('1'))>t or n<t) and n>=0:
    t+=1
    n-=p
if n<0:
    print(-1)
else:
    print(t)

Input: 6 0
1 1
Input: 11 1
Input: 13 0
Input: 14 -1
Input: 12 0
24 1
Input: 7 1
Input: 1 1
Input: 6 1
Input: 1 -1
Input: 3 1
Input: 9 -1
24 0
Input: 5 -1
Input: 11 0
24 -1
Input: 3 -1
Input: 6 -1
Input: 2 1
Input: 4 1
Input: 12 1
Input: 8 1
Input: 5 1
Input: 8 0
Input: 9 0
Input: 1 0
Input: 10 0
Input: 7 -1
Input: 14 1
Input: 13 1
Input: 4 -1
1 0
Input: 7 0
Input: 12 -1
Input: 2 0
Input: 4 0
1999 999
Input: 5 0
Input: 10 -1
Input: 11 -1
Input: 3 0
536870812 1
Input: 13 -1
Input: 10 1
Input: 14 0
4 -7
Input: 2 -1
Input: 9 1
Input: 8 -1

#include <bits/stdc++.h>
const long long INF = 2000000005;
const long long BIG_INF = 2000000000000000005;
const long long mod = 1000000007;
const long long P = 31;
const long double PI = 3.141592653589793238462643;
const double eps = 1e-9;
using namespace std;
vector<pair<long long, long long> > dir = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
bool valid(long long x, long long y, long long n, long long m) {
  return x >= 0 && y >= 0 && x < n && y < m;
}
mt19937 rng(1999999973);
signed main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  ;
  long long n, p;
  cin >> n >> p;
  for (long long i = 1; i < 1000000; i++) {
    if (n - p * i > 0 && __builtin_popcountll(n - p * i) <= i &&
        n - p * i >= i) {
      cout << i;
      return 0;
    }
  }
  cout << -1;
  return 0;
}


n,h=input().split()
n=int(n)
h=int(h)
l=list(map(int,input().split()))
k=[]
r=0
for i in range(n):
    k.append(l[i])
    k.sort(reverse=True)
    ans=0
    for j in range(0,len(k),2):
        ans=ans+k[j]
    if(ans<=h):
        r=i+1
    else:
        break
print(r)

#include <bits/stdc++.h>
using namespace std;
int main() {
  int n;
  long long int h;
  cin >> n >> h;
  long long int a[n];
  for (int i = 0; i < n; i++) {
    cin >> a[i];
  }
  int sum = 0;
  int count = 0;
  for (int i = 0; i < n; i += 1) {
    long long int sum = 0;
    sort(a, a + i + 1);
    for (int j = i; j >= 0; j -= 2) {
      sum += a[j];
    }
    if (sum <= h)
      count = i + 1;
    else
      break;
  }
  cout << count;
  return 0;
}


# alpha = "abcdefghijklmnopqrstuvwxyz"
prime = 998244353
# INF = 100000000000
# from heapq import heappush
from collections import defaultdict, deque
t = 1#int(input())
from math import sqrt
for test in range(t):
    n = int(input())
    p = [0, 0]
    p.extend(list(map(int, input().split())))
    s = [0]
    s.extend(list(map(int, input().split())))
    a = [0 for i in range(n+1)]
    a[1] = s[1]
    D = defaultdict(list)
    depth = {}
    depth[1] = 1
    # S[1] =
    for i in range(2,n+1):
        D[p[i]].append(i)
        depth[i] = depth[p[i]]+1
    q = deque([])
    q.append(1)

    found = True
    while q:
        cur = q.popleft()
        if not found:
            break
        for j in D[cur]:
            if depth[j]%2==0:
                if D[j]==[]:
                    a[j] = 0
                    s[j] = s[cur]
                else:
                    tmp = 2000000000
                    for k in D[j]:
                        tmp = min(tmp, s[k] - s[cur])
                    if tmp<0:
                        found = False
                        break
                    a[j] = tmp
                    s[j] = s[cur]+tmp
                    for k in D[j]:
                        a[k] = s[k]-tmp-s[cur]

            else:
                if a[k]<0:
                    # print(k,a[k])
                    found = False
                    break
            q.append(j)
    if found:
        print(sum(a))
    else:
        print(-1)

#include <bits/stdc++.h>
using namespace std;
const int N = 1e5;
vector<int> graph[N];
int a[N];
int s[N];
void DFS(int u, int p) {
  if (s[u] == -1) {
    int best = INT_MAX;
    for (int v : graph[u]) {
      if (v != p) {
        best = min(best, s[v]);
      }
    }
    if (best == INT_MAX) {
      best = s[p];
    }
    s[u] = best;
    if (s[u] < s[p]) {
      cout << -1;
      exit(0);
    }
    a[u] = s[u] - s[p];
  } else {
    if (p == -1) {
      a[u] = s[u];
    } else {
      a[u] = s[u] - s[p];
    }
  }
  for (int v : graph[u]) {
    if (v != p) {
      DFS(v, u);
    }
  }
}
int main() {
  ios_base::sync_with_stdio(false);
  int n;
  cin >> n;
  for (int i = 1; i < n; i++) {
    int p;
    cin >> p;
    graph[i].push_back(p - 1);
    graph[p - 1].push_back(i);
  }
  for (int i = 0; i < n; i++) {
    cin >> s[i];
  }
  DFS(0, -1);
  cout << accumulate(a, a + n, 0LL);
  return 0;
}


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

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

/* Name of the class has to be "Main" only if the class is public. */
public class Main
{
	public static void main (String[] args) throws java.lang.Exception
	{
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int a[] = new int[n];
		int count = 0;
		for(int i = 0; i < n; i++)
		{
		    a[i] = sc.nextInt();
		}
		for(int i = 1; i < n-1; i++)
		{
		    if(a[i-1] == 1 && a[i+1] == 1 && a[i] == 0)
		    {
		        a[i+1] = 0;
		        count +=1;
		    }
		}
		System.out.println(count);
	}
}

#include <bits/stdc++.h>
using namespace std;
const int maxN = 1e5 + 1;
const int mod = 1e9 + 7;
long long n, a[maxN];
inline void FastInput() {
  ios_base::sync_with_stdio(false);
  cin.tie(nullptr);
}
void ReadInput() {
  cin >> n;
  for (int i = 1; i <= n; i++) cin >> a[i];
}
void Solve() {
  long long res = 0;
  for (int i = 2; i <= n; i++) {
    if (a[i] == 0 && a[i + 1] == 1 && a[i - 1] == 1) {
      res++;
      a[i + 1] = 0;
    }
  }
  cout << res;
}
int main() {
  FastInput();
  ReadInput();
  Solve();
}


#include <bits/stdc++.h>
using namespace std;
const long long INF = 1e9 + 322;
const long long LINF = 2e18 + 474;
const long long MAXN = 1e3 + 5;
const long long MOD = 1e9 + 7;
const double eps = 1e-10;
int n, s;
int a[MAXN], b[MAXN];
string ans = "NO";
void solve() {
  cin >> n >> s;
  for (int i = 1; i <= n; i++) cin >> a[i];
  for (int i = 1; i <= n; i++) cin >> b[i];
  if (a[1] == 1) {
    if (a[s] == 1) {
      ans = "YES";
    }
    for (int i = s; i <= n; i++) {
      if (a[i] && b[i] && b[s]) {
        ans = "YES";
      }
    }
  }
  cout << ans;
}
int main() {
  if (!1) {
    freopen(
        "474"
        ".in",
        "r", stdin);
    freopen(
        "474"
        ".out",
        "w", stdout);
  }
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  setlocale(LC_ALL, "Russian");
  int T = 1;
  while (T--) {
    solve();
  }
  return 0;
}

YES NO YES YES YES YES YES YES YES YES YES YES YES YES YES YES YES YES YES YES YES YES YES YES YES YES YES YES YES YES YES YES YES YES YES YES YES YES YES YES YES YES YES YES YES YES YES YES YES NO

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

public class Main {
	public static void main(String[] args) {
	Scanner sc = new Scanner(System.in);
	int n = sc.nextInt(),s=sc.nextInt();
	int[] arr = new int[n];
	int[] brr = new int[n];
	for(int i=0;i<n;i++){arr[i]=sc.nextInt();}
	for(int i=0;i<n;i++){brr[i]=sc.nextInt();}
	if(arr[0] == 0){System.out.println("NO");return;}
	if(arr[s-1] == 0 && brr[s-1]==0){System.out.println("NO");return;}
	if(arr[s-1]==1){System.out.println("YES");return;}
	if(brr[s-1]==1){
		for(int i=n-1;i>=0;i--){
			if(arr[i]==1&&brr[i]==1){
				if(i>s-1) {System.out.println("YES");return;}
				if(i<s-1) {System.out.println("NO");return;}
			}
		}
	}System.out.println("NO");

	}
}


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

import static java.lang.Math.*;

public class cfs493B {

    public static void main(String[] args) {
        FastScanner sc = new FastScanner();
        StringBuilder sb = new StringBuilder();
        int n = sc.nextInt();
        int b = sc.nextInt();
        int[] nums = sc.readIntArray(n);
        int parity = 0;
        ArrayList<Integer> options = new ArrayList<Integer>();
        for (int i = 0; i < n-1; i++) {
            if (nums[i]%2==0) {
                parity++;
            } else {
                parity--;
            }
            if (parity == 0) {
                options.add(abs(nums[i] - nums[i+1]));
            }
        }
        Collections.sort(options);
        int sum = 0;
        int count = 0;
        while (count < options.size() && ((options.get(count) + sum ) <= b)) {
            sum += options.get(count);
            count++;
        }
        sb.append(count);

        System.out.print(sb);
    }

    public static class FastScanner {
        BufferedReader br;
        StringTokenizer st;

        public FastScanner(Reader in) {
            br = new BufferedReader(in);
        }

        public FastScanner() {
            this(new InputStreamReader(System.in));
        }

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

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

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

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

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

        int[] readIntArray(int n) {
            int[] a = new int[n];
            for (int idx = 0; idx < n; idx++) {
                a[idx] = nextInt();
            }
            return a;
        }

        long[] readLongArray(int n) {
            long[] a = new long[n];
            for (int idx = 0; idx < n; idx++) {
                a[idx] = nextLong();
            }
            return a;
        }
    }
}

n, b = input().split()
n = int(n)
b = int(b)
a = [int(x) for x in input().split()]
odd = 0
not_odd = 0
pos = list()
for i in range(n-1):
    if a[i] % 2 == 0:
        not_odd += 1
    else:
        odd += 1
    if not_odd == odd:
          pos.append(abs(a[i+1] - a[i]))
pos.sort()
sum = 0
count = 0
for i in range(len(pos)):
    if sum + pos[i] <= b:
        sum += pos[i]
        count += 1
print(count)


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

public class ProbC {
	public static void main(String[] args) {
		ProbC sol = new ProbC();
		sol.start();
	}

	StringBuffer printstr;
	String _readerstr;
	BufferedReader rdr;
	HashSet<Integer> debug_number_set;
	int[] debug_code;

	public void print(Object o){ print(o, 0); }
	public void print(Object o, int debug_number){
		if(debug_number_set.contains(debug_number)) System.out.print(o);
	}
	public void println() { print("\n", 0); }
	public void println(Object o) { println(o, 0); }
	public void println(Object o, int debug_number){ print(o+"\n", debug_number); }

	public void bufp(Object o){ printstr.append(o); }
	public void bufpl(Object o){ printstr.append(o).append('\n'); }
	public void bufpl() { printstr.append('\n'); }
	public void bufp(char[] c, int offset, int len){ printstr.append(c, offset, len); }
	public void bufpl(char[] c, int offset, int len){ printstr.append(c, offset, len).append('\n'); }

	public Integer readInt(){
		try{
			if(_readerstr==null) _readerstr = rdr.readLine();
		}
		catch(Exception e){ return null; }
		String[] s = _readerstr.split(" ", 2);
		if(s.length==1) _readerstr = null;
		else _readerstr = s[1];
		try{
			return Integer.parseInt(s[0]);
		}
		catch(Exception e){}
		return readInt();
	}

	public Long readLong(){
		try{
			if(_readerstr==null) _readerstr = rdr.readLine();
		}
		catch(Exception e){ return null; }
		String[] s = _readerstr.split(" ", 2);
		if(s.length==1) _readerstr = null;
		else _readerstr = s[1];
		try{
			return Long.parseLong(s[0]);
		}
		catch(Exception e){}
		return readLong();
	}

	public Double readDouble(){
		try{
			if(_readerstr==null) _readerstr = rdr.readLine();
		}
		catch(Exception e){ return null; }
		String[] s = _readerstr.split(" ", 2);
		if(s.length==1) _readerstr = null;
		else _readerstr = s[1];
		try{
			return Double.parseDouble(s[0]);
		}
		catch(Exception e){}
		return readDouble();
	}

	public String readStr(){
		try{
			if(_readerstr==null) _readerstr = rdr.readLine();
		}
		catch(Exception e){ return null; }
		String[] s = _readerstr.split(" ", 2);
		if(s.length==1) _readerstr = null;
		else _readerstr = s[1];
		return s[0];
	}

	public String readLine(){
		try{
			if(_readerstr==null) _readerstr = rdr.readLine();
		}
		catch(Exception e){ return null; }
		String ret = _readerstr;
		_readerstr = null;
		return ret;
	}

	public void initiate_the_entire_program(){
		printstr = new StringBuffer();
		_readerstr = null;
		try{
			rdr = new BufferedReader(new InputStreamReader(System.in));
		}
		catch(Exception e){ println(e); }
		debug_number_set = new HashSet();
		for(int i : debug_code) debug_number_set.add(i);
	}

	public void start(){
		debug_code = new int[] {0,1,2,3,4,5};
		initiate_the_entire_program();

		submit();
//		test();

		System.out.println(printstr);
		System.out.flush();
	}

	public void test(){
		bufpl(2000+" "+500);
		for(int i=0;i<2000;i++) bufp(1+" ");
		bufpl(" ");
		for(int i=0;i<500;i++) bufp((i*2)+" ");
		bufpl(" ");
	}

	public void submit(){
		int k = readInt(), n = readInt();
		int[] a = new int[k], b = new int[n];
		for(int i=0;i<k;i++) a[i] = readInt();
		for(int i=0;i<n;i++) b[i] = readInt();
		bufpl(marks(k,n,a,b));
	}

	public int marks1(int k, int n, int[] a, int[] b){
		int[] p = new int[k];
		p[0] = 0;
		for(int i=1;i<k;i++) p[i] = p[i-1] + a[i];
		Arrays.sort(p);
		Arrays.sort(b);
		int m = 0;
		for(int i=0;i<k-1;i++) if(p[i+1]>p[i]) m++;

		int[] seq = new int[m];
		int[] pattern = new int[n-1];
		int j=0;
		for(int i=0;i<k-1;i++) if(p[i+1]>p[i]) seq[j++] = p[i+1] - p[i];
		for(int i=0;i<n-1;i++) pattern[i] = b[i+1] - b[i];
		return search(seq, pattern);
	}

	public int marks(int k, int n, int[] a, int[] b){
		for(int i=1;i<k;i++) a[i] += a[i-1];
		Arrays.sort(a);
		Arrays.sort(b);
		int m = 1;
		for(int i=0;i<k-1;i++) if(a[i+1]>a[i]) m++;

		int[] seq = new int[m];
		int j=1;
		seq[0] = a[0];
		for(int i=0;i<k-1;i++) if(a[i+1]>a[i]) seq[j++] = a[i+1];
		return search(seq, b);
	}

	public int search(int[] seq, int[] pattern){
		//return the number of x, so that
		//pattern[] + x is a subseq (not necessarily continuous) of seq[]
		//both seq[] and pattern are supposed to be strictly increasing
		int n = seq.length;
		int m = pattern.length;
		int ret = 0;
		HashMap<Integer, Integer> map = new HashMap();
		for(int i=0;i<n;i++) map.put(seq[i], i);
		boolean[][] match = new boolean[n][m];
		for(int i=n-1;i>=0;i--) for(int j=m-1;j>=0;j--){
			if(j==m-1) match[i][j] = true;
			else if(i==n-1) match[i][j] = false;
			else{
				Integer k = map.get(seq[i]-pattern[j]+pattern[j+1]);
				if(k==null || match[k][j+1]==false) match[i][j] = false;
				else match[i][j] = true;
			}
		}

		for(int i=0;i<n;i++) if(match[i][0]) ret += 1;
		return ret;
	}
}

#include <bits/stdc++.h>
using namespace std;
map<int, int> mp;
set<int> s;
int a[2345];
int b[2345];
int sum[2345];
int main() {
  mp.clear();
  s.clear();
  int k, n, h = 0, flag = 1;
  scanf("%d %d", &k, &n);
  for (int i = 0; i < k; i++) {
    scanf("%d", &a[i]);
    if (i) {
      sum[i] = a[i] + sum[i - 1];
      mp[sum[i]] = 1;
    } else {
      sum[i] = a[i];
      mp[sum[i]] = 1;
    }
  }
  for (int i = 0; i < n; i++) {
    scanf("%d", &b[i]);
  }
  for (int i = 0; i < k; i++) {
    int t = b[0] - sum[i];
    if (i == 0 || sum[i] != sum[i - 1]) {
      for (int j = 1; j < n; j++) {
        if (!mp[b[j] - t]) {
          flag = 0;
          break;
        }
      }
      if (flag) s.insert(t);
      flag = 1;
    }
  }
  printf("%d\n", (int)s.size());
  return 0;
}


#!/usr/bin/env python
import sys
def eligible(score, position, thresh):
    if score < thresh:
        return False
    i = (score // 50) % 475
    for __ in range(25):
        i = (i * 96 + 42) % 475
        if position == 26 + i:
            return True
    return False

def main():
    p, x, y= map(int, sys.stdin.readline().split())
    diff = 0
    for __ in range(475):
        if eligible(x + diff, p, y):
            print("0")
            return
        diff -= 50
    diff = 0
    for __ in range(475):
        if eligible(x + diff, p, y):
            succ = diff // 100
            unsucc = (diff // 50) %2 ## if 1, we need additional success
            print(str(succ + unsucc))
            return
        diff += 50

main()

#include <bits/stdc++.h>
using namespace std;
int p, x, y;
bool check(int a) {
  a /= 50;
  a %= 475;
  for (int i = 0; i < 25; ++i) {
    a = (a * 96 + 42) % 475;
    if (a + 26 == p) return true;
  }
  return false;
}
int solve() {
  int a = x;
  a = (y / 50) * 50 + x % 50;
  if (a < y) a += 50;
  while (a < x) {
    if (check(a)) return 0;
    a += 50;
  }
  int res = 0;
  while (!check(a)) {
    ++res;
    a += 50;
    if (!check(a)) a += 50;
  }
  return res;
}
int main() {
  cin >> p >> x >> y;
  cout << solve() << endl;
  return 0;
}


#include <bits/stdc++.h>
#pragma comment(linker, "/STACK:500000000")
using namespace std;
int main() {
  int n, k, i;
  scanf("%d %d", &n, &k);
  vector<int> a(n);
  for (i = 0; i < n; i++) scanf("%d", &a[i]);
  sort(a.begin(), a.end());
  int L, R;
  L = 0, R = a.back();
  int RR = R;
  while (L <= R) {
    int c = (L + R) / 2;
    long long sm = 0;
    for (auto p : a)
      if (p >= c) sm += p - c;
    if (sm <= k)
      R = c - 1, RR = c;
    else
      L = c + 1;
  }
  L = 0, R = a.back();
  int LL = 0;
  while (L <= R) {
    int c = (L + R) / 2;
    long long sm = 0;
    for (auto p : a)
      if (c >= p) sm += c - p;
    if (sm <= k)
      L = c + 1, LL = c;
    else
      R = c - 1;
  }
  auto diff = RR - LL;
  if (diff <= 0) {
    long long sum = 0;
    for (auto p : a) sum += p;
    if (sum % n == 0)
      diff = 0;
    else
      diff = 1;
  }
  cout << diff << endl;
}

import java.io.*;

public class Round532D {
    public static void main(String[] args) throws Exception {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        String[] line = in.readLine().split(" ");
        int n = Integer.parseInt(line[0]);
        int k = Integer.parseInt(line[1]);
        line = in.readLine().split(" ");
        int[] a = new int[n];
        int min = 1000000000;
        int max = 0;
        long sum = 0;
        for (int i = 0; i < n; i++) {
            a[i] = Integer.parseInt(line[i]);
            sum += a[i];
            min = Math.min(min, a[i]);
            max = Math.max(max, a[i]);
        }
        int l = min;
        int r = max;
        while (l <= r) {
            int mid = l + (r - l) / 2;
            long s = 0;
            for (int i = 0; i < n; i++) {
                s += Math.max(0, mid - a[i]);
            }
            if (s <= k) {
                min = mid;
                if (s == k) break;
                l = mid + 1;
            } else {
                r = mid - 1;
            }
        }
        l = min;
        r = max;
        while (l <= r) {
            int mid = l + (r - l) / 2;
            long s = 0;
            for (int i = 0; i < n; i++) {
                s += Math.max(0, a[i] - mid);
            }
            if (s <= k) {
                max = mid;
                if (s == k) break;
                r = mid - 1;
            } else {
                l = mid + 1;
            }
        }
        int ans = max - min;
        if (ans <= 0 && sum % n != 0) ans = 1;
        System.out.println(ans);
    }
}


n, k, x = map(int, input().split())
A = list(map(int, input().split()))

L, R = [0]*(n+1), [0]*(n+1)
for i in range(n):
    L[i+1] = A[i] | L[i]
for i in range(n-1, -1, -1):
    R[i] = A[i] | R[i+1]
x = x**k

ans = 0
for i in range(n):
    ans = max(ans, L[i] | (A[i]*x) | R[i+1])

print(ans)

#include <bits/stdc++.h>
using namespace std;
long long a[200002];
long long Left[200002];
long long Right[200002];
int main() {
  int n, k, x;
  cin >> n >> k >> x;
  memset(Left, 0, sizeof Left);
  memset(Right, 0, sizeof Right);
  for (int i = 1; i <= n; i++) cin >> a[i];
  for (int i = 1; i <= n; i++) {
    Left[i] = Left[i - 1] | a[i];
  }
  for (int i = n; i >= 1; i--) {
    Right[i] = Right[i + 1] | a[i];
  }
  long long ans = 0;
  for (int pos = 1; pos <= n; pos++) {
    long long tem = a[pos];
    for (int i = 1; i <= k; i++) {
      tem = tem * x;
    }
    ans = max(ans, Left[pos - 1] | tem | Right[pos + 1]);
  }
  cout << ans << endl;
  return 0;
}


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

public class Competencia3 {

	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		int n = scan.nextInt();
		int[] X = new int[n];
		int[] Y = new int[n];
		for(int i = 0; i < n; i++) {
			X[i] = scan.nextInt();
			Y[i] = scan.nextInt();

		}

		int res = 0;
		for(int i = 0; i < n; i++) {
			for(int j = i + 1; j < n; j++) {
				int punto1 = X[j] - X[i];
                int punto2 = Y[j] - Y[i];
                int punto3 = X[j] * Y[i] - Y[j] * X[i];
				for(int k = j + 1; k < n; k++) {
					if(punto1 * Y[k] - punto2 * X[k] != punto3) {
						res++;
					}
				}
			}
		}
		System.out.println(res);
		scan.close();
	}
}

import sys
from math import gcd
from collections import defaultdict
input=sys.stdin.readline
n=int(input())
p=[list(map(int,input().split())) for i in range(n)]
ans=0
for xi,yi in p:
    angle=defaultdict(int)
    for x,y in p:
        if xi==x and yi==y:
            continue
        x-=xi;y-=yi
        if x<0 or (x==0 and y<0):
            x=-x;y=-y
        g=abs(gcd(x,y))
        x//=g;y//=g
        angle[(x,y)]+=1
    cnt=0
    for i in angle.keys():
        cnt+=angle[i]*(n-1-angle[i])
    ans+=cnt//2
print(ans//3)


import operator as op
import re
import sys
from bisect import bisect, bisect_left, insort, insort_left
from collections import Counter, defaultdict, deque
from copy import deepcopy
from decimal import Decimal
from functools import reduce
from itertools import (
    accumulate, combinations, combinations_with_replacement, groupby,
    permutations, product)
from math import (acos, asin, atan, ceil, cos, degrees, factorial, gcd, hypot,
                  log2, pi, radians, sin, sqrt, tan)
from operator import itemgetter, mul
from string import ascii_lowercase, ascii_uppercase, digits

def inp():
    return(int(input()))

def inlist():
    return(list(map(int, input().split())))

def instr():
    s = input()
    return(list(s[:len(s)]))

def invr():
    return(map(int, input().split()))

def def_value():
    return 0

def e_gcd(a, b, res):
    if a == b or b == 0:
        return res
    res += a // b
    return e_gcd(b, a % b, res)

# For getting input from input.txt file
#sys.stdin = open('input.txt', 'r')
# Printing the Output to output.txt file
# sys.stdout = open('output.txt', 'w')

a, b = invr()
res = e_gcd(a, b, 0)
print(res)

//package com.company;
import java.util.*;
public class Main {

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);

        long a,b;
        a= scan.nextLong();
        b= scan.nextLong();
        long counter=0;
        long temp;

        while( b % a != 0  )
        {
            counter+= a/b;
            a = a%b;
            if(b > a)
            {
                temp =a;
                a=b;
                b= temp;
            }
        }

        if(a==b)
            counter++;

        System.out.println(counter);
    }
}


import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class C {

    class E implements Comparable<E>{
        int id, deg, xor;
        public E(int id, int deg, int xor) {
            this.id = id;
            this.deg = deg;
            this.xor = xor;
        }
        @Override
        public int compareTo(E o) {
            return deg-o.deg;
        }
    }
    E[] nodes;

    void run(){
        Scanner sc = new Scanner();
        int n = sc.nextInt();
        nodes = new E[n];
        Queue<Integer> q = new LinkedList<Integer>();
        for(int i=0;i<n;i++){
            nodes[i] = new E(i, sc.nextInt(), sc.nextInt());
            if(nodes[i].deg==1)q.add(i);
        }
        List<int[]> res = new ArrayList<int[]>();
        while(!q.isEmpty()){
            int id = q.poll();
            while(nodes[id].deg==1){
                int adj = nodes[id].xor;
                res.add(new int[]{id, adj});
                nodes[id].deg--;
                nodes[adj].deg--;
                nodes[id].xor^=adj;
                nodes[adj].xor^=id;
                if(nodes[adj].deg==1)id=adj;
                else break;
            }
        }
        System.out.println(res.size());
        for(int[]a:res)System.out.println(a[0]+" "+a[1]);
    }

    class Scanner {
        int nextInt() {
            try {
                int c = System.in.read();
                while (c != '-' && (c < '0' || '9' < c))
                    c = System.in.read();
                if (c == '-') return -nextInt();
                int res = 0;
                do {
                    res *= 10;
                    res += c - '0';
                    c = System.in.read();
                } while ('0' <= c && c <= '9');
                return res;
            } catch (Exception e) {
                return -1;
            }
        }
    }

    void debug(Object...o){
        System.out.println(Arrays.deepToString(o));
    }

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

from collections import defaultdict

def main():
    n = int(input())
    bydegree = defaultdict(set)
    bys = defaultdict(set)
    l = []
    for i in range(n):
        degree, s = map(int, input().split())
        bydegree[degree].add(i)
        bys[s].add(i)
        l.append((degree, s))
    res = []
    ones = bydegree[1]
    while ones:
        i = ones.pop()
        degree_i, j = l[i]
        degree_j, s = l[j]
        res.append(' '.join((str(i), str(j))))
        bydegree[degree_j].remove(j)
        degree_j -= 1
        bydegree[degree_j].add(j)
        l[j] = (degree_j, s ^ i)
    print(len(res))
    print('\n'.join(res))

if __name__ == '__main__':
    main()


n = int(input())
listd = []
res = 0

for i in range(n):
    listd.append(tuple(map(int, input().split())))
listd.sort()

for a, b in listd:
    res = b if res<=b else a

print(res)

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

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

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

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

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

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

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

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

    static class Value
    {
        int a; int b;

    }
    static class Comparator1 implements Comparator<Value> {
        public int compare(Value v1,Value v2)
        {
            if(v1.a>v2.a)
            {return 1;}
            if(v1.a<v2.a)
            {return -1;}
            if(v1.a==v2.a&& v1.b!=v2.b)
            {return v1.b>v2.b?1:-1;}
            return 0;
        }
    }
    public static void main (String[] args) throws java.lang.Exception
    {
        FastReader sc= new FastReader();
        BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out));
         //int t=sc.nextInt();
         //for(int j=0;j<t;j++)
         //{
            int n=sc.nextInt();
            Value arr[]= new Value[n];

            for(int i=0;i<n;i++)
            {
                Value v=new Value();
                v.a=sc.nextInt();
                v.b=sc.nextInt();
                arr[i]=v;
            }
            Arrays.sort(arr,new Comparator1());
            int max=0;
            for(int i=0;i<n;i++)
            {
                //System.out.println(arr[i].a+" "+arr[i].b);
                if(arr[i].b>=max)
                {max=arr[i].b;}
                else
                {max=arr[i].a;}
            }

            output.write(max+"");output.flush();
         //}

    }

}


import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.InputMismatchException;

public class LongPath {
	static class Solver {

		int N, p[], exit[];
		int add(int a, int b) { return (a + b) % 1_000_000_007; }

		void solve(int testNumber, FastScanner s, PrintWriter out) {
			N = s.nextInt(); p = new int[N]; exit = new int[N];
			for(int i = 0; i < N; i++) p[i] = s.nextInt() - 1;

			Arrays.fill(exit, 2);
			int res = 2;
			for(int i = 1; i < N; i++) {
				int j = p[i];
				while(j < i) exit[i] = add(exit[i], exit[j++]);
				res = add(res, exit[i]);
			}
			out.println(res);
		}

	}

	final static boolean cases = false;

	public static void main(String[] args) {

		FastScanner s = new FastScanner(System.in);
		PrintWriter out = new PrintWriter(System.out);

		Solver solver = new Solver();
		for (int t = 1, T = cases ? s.nextInt() : 1; t <= T; t++)
			solver.solve(t, s, out);

		out.close();

	}

	static int min(int a, int b) {
		return a < b ? a : b;
	}

	static int max(int a, int b) {
		return a > b ? a : b;
	}

	static long min(long a, long b) {
		return a < b ? a : b;
	}

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

	static int swap(int a, int b) {
		return a;
	}

	static Object swap(Object a, Object b) {
		return a;
	}

	static String ts(Object... o) {
		return Arrays.deepToString(o);
	}

	static class FastScanner {
		private InputStream stream;
		private byte[] buf = new byte[1024];
		private int curChar;
		private int numChars;

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

		public FastScanner(File f) throws FileNotFoundException {
			this(new FileInputStream(f));
		}

		public FastScanner(String s) {
			this.stream = new ByteArrayInputStream(s.getBytes(StandardCharsets.UTF_8));
		}

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

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

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

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

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

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

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

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

		// Jacob Garbage

		public int[] nextIntArray(int N) {
			int[] ret = new int[N];
			for (int i = 0; i < N; i++)
				ret[i] = this.nextInt();
			return ret;
		}

		public int[][] next2DIntArray(int N, int M) {
			int[][] ret = new int[N][];
			for (int i = 0; i < N; i++)
				ret[i] = this.nextIntArray(M);
			return ret;
		}

		public long[] nextLongArray(int N) {
			long[] ret = new long[N];
			for (int i = 0; i < N; i++)
				ret[i] = this.nextLong();
			return ret;
		}

		public long[][] next2DLongArray(int N, int M) {
			long[][] ret = new long[N][];
			for (int i = 0; i < N; i++)
				ret[i] = nextLongArray(M);
			return ret;
		}

		public double[] nextDoubleArray(int N) {
			double[] ret = new double[N];
			for (int i = 0; i < N; i++)
				ret[i] = this.nextDouble();
			return ret;
		}

		public double[][] next2DDoubleArray(int N, int M) {
			double[][] ret = new double[N][];
			for (int i = 0; i < N; i++)
				ret[i] = this.nextDoubleArray(M);
			return ret;
		}

	}
}

#include <bits/stdc++.h>
using namespace std;
const int inf = 1e9, maxn = 2e5 + 5, mod = 1e9 + 7;
int n, a[maxn], dp[maxn];
int main() {
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
  dp[1] = 0;
  for (int i = 2; i <= n + 1; i++)
    dp[i] = (dp[i - 1] * 2ll % mod + mod - dp[a[i - 1]] + 2) % mod;
  printf("%d\n", dp[n + 1]);
  return 0;
}


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

public class Main {
    public static StreamTokenizer st;
    public static PrintWriter cout;
    public static int nextInt() throws IOException {
        st.nextToken();
        return (int)(st.nval);
    }
    public static double nextDouble() throws IOException {
        st.nextToken();
        return (double)(st.nval);
    }
    public static long nextlong() throws IOException {
        st.nextToken();
        return (long)(st.nval);
    }
    public static void init() throws IOException {
        st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
        cout = new PrintWriter(new OutputStreamWriter(System.out));
    }

    public static int[] head = new int[1000000];
    public static int[] link = new int[2000000];
    public static int[] dest = new int[2000000];
    public static int[] tmp = new int[1000000];
    public static int g_sz = 0;
    public static int tmp_sz = 0;
    public static long[] hash1 = new long[1000000];
    public static long[] hash2 = new long[1000000];
    public static void add_arc(int u, int v) {
        dest[g_sz] = v;
        link[g_sz] = head[u];
        head[u] = g_sz++;

        dest[g_sz] = u;
        link[g_sz] = head[v];
        head[v] = g_sz++;
    }
    public static void get_hashes(int id) {
        long p = 1000000007;
        long sum1 = 0, sum2 = 0;
        long pow1 = 1, pow2 = 1;
        for (int i = 0; i < tmp_sz; ++i) {
            if (tmp[i] > id && (i == 0 || tmp[i - 1] < id)) {
                sum1 += pow1 * (id + 1);
                pow1 *= p;
            }
            sum1 += pow1 * (tmp[i] + 1);
            sum2 += pow2 * (tmp[i] + 1);
            pow1 *= p;
            pow2 *= p;
        }
        if (tmp_sz == 0 || id > tmp[tmp_sz - 1]) {
            sum1 += pow1 * (id + 1);
        }
        hash1[id] = sum1;
        hash2[id] = sum2;
        //cout.println(sum1 + " " + sum2);
    }
    public static void main(String[] argc) throws IOException {
        init();
        int n = nextInt();
        int m = nextInt();
        for (int i = 0; i < n; ++i) {
            head[i] = -1;
        }
        for (int i = 0; i < m; ++i) {
            int u = nextInt();
            int v = nextInt();
            add_arc(u - 1, v - 1);
        }
        for (int i = 0; i < n; ++i) {
            tmp_sz = 0;
            for (int arc = head[i]; arc != -1; arc = link[arc]) {
                tmp[tmp_sz++] = dest[arc];
            }
           // cout.println("SZ = " + tmp_sz);
            Arrays.sort(tmp, 0, tmp_sz);
            get_hashes(i);
        }
        Arrays.sort(hash1, 0, n);
        Arrays.sort(hash2, 0, n);
        //cout.flush();

        int p1 = 0, p2 = 0;
        long ans = 0;
        for (int i = 1; i <= n; ++i) {
            if (i == n || hash1[i] != hash1[p1]) {
                long cur = i - p1;
                ans += cur * (cur - 1) / 2;
                p1 = i;
            }
            if (i == n || hash2[i] != hash2[p2]) {
                long cur = i - p2;
                ans += cur * (cur - 1) / 2;
                p2 = i;
            }
        }
        cout.println(ans);
        cout.flush();
    }
}

#include <bits/stdc++.h>
using namespace std;
long long p[1000005], h[1000005];
unordered_map<long long, long long> m1, m2;
int main() {
  long long ans = 0, n, m, B = 37, x, y;
  m1.reserve(1 << 12), m2.reserve(1 << 12);
  m1.max_load_factor(0.25), m2.max_load_factor(0.25);
  scanf("%lld%lld", &n, &m), p[0] = 1;
  for (long long i = 1; i < 1000005; i++) p[i] = p[i - 1] * B;
  while (m--) scanf("%lld%lld", &x, &y), h[x] += p[y], h[y] += p[x];
  for (long long i = 1; i <= n; i++) m1[h[i]]++, h[i] += p[i], m2[h[i]]++;
  for (auto i : m1) ans += (i.second * (i.second - 1)) / 2;
  for (auto i : m2) ans += (i.second * (i.second - 1)) / 2;
  cout << ans;
}


#include <bits/stdc++.h>
using namespace std;
const int N = 500005, mod = 1000000007;
long long int a, b, c, d, e, f, g, h[N], arr[N];
string s;
vector<long long int> v;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  cin >> a >> s;
  long long int say = 0, ans = 0;
  for (long long int i = 0; i < a; i++) {
    if (s[i] == ')') {
      if (say > 0)
        say--;
      else {
        long long int bas = i;
        say--;
        while (i < a and say < 0) say += (s[++i] == '(' ? 1 : -1);
        if (say != 0) {
          cout << -1 << endl;
          return 0;
        }
        ans += i - bas + 1;
      }
    } else {
      say++;
    }
  }
  if (say != 0)
    cout << -1 << endl;
  else
    cout << ans << endl;
}

n=int(input())
l=input()
e=[]
p=0
for i in l:
    if i=='(':
        p+=1
        e.append(p)
    else:
        p-=1
        e.append(p)
if e[-1]!=0:
    print(-1)
else:
    ans=0
    z=0
    for i in range(n):
        if e[i]<0:
            z+=1
        else:
            if z>0:
                ans+=z+1
                z=0
    print(ans)


s=input()
n=len(s)
b=[]
for j in s:
    b.append(j)
x=[]
y=[]
j=0
i=n-1
while(j<i):
    if b[j]==b[i]:
        if i!=j:
            x.append(b[j])
            y.append(b[i])
        else:
            x.append(b[j])
        i+=-1
        j+=1
    elif b[j]==b[i-1]:
        if (i-1) != j:
            x.append(b[j])
            y.append(b[i-1])
        else:
            x.append(b[j])
        j+=1
        i+=-2
    else:
        if b[j+1]==b[i]:
            if i!=(j+1):
                x.append(b[j+1])
                y.append(b[i])
            elif i==(j+1):
                x.append(b[j + 1])
            i+=-1
            j+=2
        else:
            if ((i-1)!= (j + 1)):
                x.append(b[j + 1])
                y.append(b[i-1])
            elif (i-1) == (j + 1):
                x.append(b[j + 1])
            i += -2
            j += 2
res=x+y[::-1]
print("".join(res))

aaa
```

Note that each input string is between 2 and 40 characters long and consists only of the characters "a", "b", and "c". Additionally, no two consecutive characters in the input strings are the same.

cbabc cacac c aba a aba bcb cbc aaa c acaca b caacabcaccbcbcbcbccacbacaac aca b bcb bbbcacbbb ababa a acbca bccabbabbaccb aba bab b bcbcbcbcb aca a a cabcbac cac bab abcba bcacb cacac cac bccabbabbaccb cacac a a c aaabcbaaa

#include <bits/stdc++.h>
using namespace std;
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  string s;
  cin >> s;
  int n = s.size();
  int l = 0, r = n - 1;
  string t = "";
  while (l + 2 < r) {
    if (s[l] != s[r]) {
      l++;
    }
    if (s[l] != s[r]) {
      r--;
    }
    if (s[l] != s[r]) {
      l--;
    }
    t += s[l];
    l++;
    r--;
  }
  cout << t;
  if (l <= r) {
    cout << s[l];
  }
  reverse(t.begin(), t.end());
  cout << t;
  return 0;
}


#include <bits/stdc++.h>
using namespace std;
int a[30];
int main() {
  int n;
  cin >> n;
  char s[105];
  while (n--) {
    memset(a, 0, sizeof(a));
    memset(s, '\0', sizeof(s));
    cin >> s;
    int l;
    l = strlen(s);
    for (int i = 0; i < l; i++) a[s[i] - 'a' + 1]++;
    string s1, s2;
    for (int i = 1; i <= 26; i++) {
      if (i % 2 == 0)
        while (a[i]--) s1 += i - 1 + 'a';
      else if (i % 2 == 1)
        while (a[i]--) s2 += i - 1 + 'a';
    }
    if (abs(s1.back() - s2.front()) > 1)
      cout << s1 << s2 << endl;
    else if (abs(s2.back() - s1.front()) > 1)
      cout << s2 << s1 << endl;
    else
      cout << "No answer" << endl;
  }
  return 0;
}

100
c
da
a
ee
ed
db
ece
ab
abe
d
eeb
a
bab
bbd
c
cab
c
bda
db
cca
bcd
bae
eb
de
dc
aee
ada
ba
ba
de
ed
ae
bc
bec
dae
c
b
dab
d
a
dbd
da
c
e
ee
be
c
a
b
c
bac
ee
a
cce
c
de
c
dee
ed
cb
b
dc
cc
a
eb
ec
bcd
a
dc
e
ced
ac
dbc
ab
cb
ceb
dce
ba
deb
dad
ace
b
adc
eaa
a
ee
baa
eeb
c
bb
ceb
b
a
bcd
b
bd
ea
bae
ea
bdb

c
da
a
ee
No answer
db
eec
No answer
aeb
d
eeb
a
No answer
dbb
c
No answer
c
adb
db
cca
No answer
aeb
eb
No answer
No answer
eea
daa
No answer
No answer
No answer
No answer
ea
No answer
bec
dae
c
b
adb
d
a
ddb
da
c
e
ee
eb
c
a
b
c
No answer
ee
a
ecc
c
No answer
c
No answer
No answer
No answer
b
No answer
cc
a
eb
ec
No answer
a
No answer
e
No answer
ca
No answer
No answer
No answer
bec
No answer
No answer
dbe
dda
aec
b
cad
eaa
a
ee
No answer
eeb
c
bb
bec
b
a
No answer
b
db
ea
aeb
ea
dbb

import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner sc=new Scanner(System.in);
		int t=sc.nextInt();
		while(t-->0){
			String s=sc.next();
			char ctr[]=s.toCharArray();
			int letter[]=new int[26];//存储每个字母出现的次数
			for(int i=0;i<ctr.length;i++){
				int num=ctr[i]-'a';
				letter[num]++;
			}
			char goal[]=new char[26];//把出现过的字母按从小到大的顺序存储一次
			int len=0;
			for(int i=0;i<26;i++){
				if(letter[i]!=0)
					goal[len++]=(char) (i+'a');
			}
			String str="";

			if(len%2==0){//分奇偶来构造
				for(int i=0;i<len/2-1;i++){
					str+=goal[i];
					str+=goal[len-i-1];
				}
				String tmp=goal[len/2]+str+goal[len/2-1];
				char ct[]=tmp.toCharArray();
				boolean flag=true;//判断构造完之后是否没有丑数
				for(int i=0;i<ct.length-1;i++){
					int num=ct[i]-ct[i+1];
					if(num==1||num==-1){
						flag=false;
						break;
					}
				}
				if(flag){
					for(int i=0;i<ct.length;i++){
						for(int j=0;j<letter[(int)(ct[i]-'a')];j++){
							System.out.print(ct[i]);
						}
					}
					System.out.println();
				}else{
					System.out.println("No answer");
				}
			}else{
				for(int i=0;i<len/2;i++){
					str+=goal[i];  //注意不能写成str+=goal[i]+goal[len-i-1],这样会先计算后两个的ascall码和，是整型
					str+=goal[len-i-1];
				}
				String tmp=str;
				tmp+=goal[len/2];
				char ct[]=tmp.toCharArray();
				boolean flag1=true;
				for(int i=0;i<ct.length-1;i++){
					int num=ct[i]-ct[i+1];
					if(num==1||num==-1){
						flag1=false;
						break;
					}
				}
				if(flag1){
					for(int i=0;i<ct.length;i++){
						for(int j=0;j<letter[ct[i]-'a'];j++){
							System.out.print(ct[i]);
						}
					}
					System.out.println();
				}else{
					tmp=goal[len/2]+str;
					char ct2[]=tmp.toCharArray();
					boolean flag2=true;
					for(int i=0;i<ct.length-1;i++){
						int num=ct2[i]-ct2[i+1];
						if(num==1||num==-1){
							flag2=false;
							break;
						}
					}
					if(flag2){
						for(int i=0;i<ct2.length;i++){
							for(int j=0;j<letter[ct2[i]-'a'];j++){
								System.out.print(ct2[i]);
							}
						}
						System.out.println();
					}else{
						System.out.println("No answer");
					}
				}
			}
		}
		sc.close();
	}
}


#include <bits/stdc++.h>
using namespace std;
const long long inf = 2e18;
const long long mod = 1e9 + 7;
const long long mod2 = 998244353;
const long long delta = 12473;
const long long maxn = 1e6 + 10;
long long p = 0, v = 0;
long long n;
long long nn;
long long power(long long a, long long b) {
  long long ans = 1;
  while (b > 0) {
    if ((long long)b % 2 == 1) ans = (a * ans);
    b /= 2;
    a = a * a;
  }
  return ans;
}
void dojob(long long k) {
  if (n <= k) {
    v += n;
    return;
  }
  v += k;
  n -= k;
  p += (long long)floor(n / 10);
  n -= (long long)floor(n / 10);
  ;
  dojob(k);
}
long long dojob2(long long l, long long r) {
  if (l == r) return l;
  long long pp = (long long)floor((l + r) / 2);
  p = 0;
  v = 0;
  n = nn;
  dojob(pp);
  if (v >= p)
    return dojob2(l, pp);
  else
    return dojob2(pp + 1, r);
}
int main() {
  cin >> nn;
  cout << dojob2(1, nn);
  return 0;
}

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

import static java.lang.System.in;

public class Main {
    public static void main(String[] args)throws IOException{
        Scanner sc = new Scanner(System.in);
        long n = sc.nextLong();
        long ans = solve(n);
        System.out.println(ans);
    }
    static long solve(long n){
        if(n==1) return 1;
        long hi = (n+1)/2, lo = 0;
        while(hi-lo>1){
            long mid = (hi+lo)/2;
            if(check(n,mid)) hi = mid;
            else lo = mid;
        }
        return hi;
    }
    static boolean check(long n, long k){
        long vas = 0,backup = n;
        while(n>0){
            vas +=  Math.min(k,n);
            n -= Math.min(k,n);
            n -= n/10;
        }
        return vas>=(backup+1)/2;
    }
}


import java.io.*;
import java.time.temporal.TemporalAmount;
import java.util.*;
import java.util.function.Consumer;

public class Solution {

    static MyScanner sc;
    private static PrintWriter out;
    static long M2 = 1_000_000_000L + 9;
    private static HashMap<Long, Long>[] mods;

    public static void main(String[] s) throws Exception {
        StringBuilder stringBuilder = new StringBuilder();
//
//        stringBuilder.append("1 25 20 30 80");

        if (stringBuilder.length() == 0) {
            sc = new MyScanner(System.in);
        } else {
            sc = new MyScanner(new BufferedReader(new StringReader(stringBuilder.toString())));
        }

        out = new PrintWriter(new OutputStreamWriter(System.out));

        initData();
        solve();
        out.flush();
    }

    private static void initData() {
//        fillPows();
//        mods = new HashMap[1001];
//        for (int i = 0; i < mods.length; i++) {
//            mods[i] = new HashMap<>();
//        }
    }

    private static void solve() throws IOException {
        int n = sc.nextInt();
        int[] r = sc.na(n);
        boolean[] vx = new boolean[1000001];
        for (int i : r) {
            vx[i] = true;
        }
        int gcd = r[0];
        for (int k : r) {
            gcd = (int) gcd(gcd, k);
        }

        int[] res = new int[r.length + r.length - 1];
        Arrays.fill(res, gcd);
        for (int t = 0; t < n; t++) {
            res[2 * t ] = r[t];
        }

        for (int t = 0; t < res.length; t++) {
            int gc = res[t];
            for (int l = t + 1; l < res.length; l++) {
                gc = (int) gcd(gc, res[l]);
                if (!vx[gc]) {
                    out.println(-1);
                    return;
                }
            }
        }
        out.println(res.length);
        for (int i : res) {
            out.print(i + " ");
        }
    }

    private static int[][] pows = new int[1001][1001];

    private static void fillPows() {
        pows[2][0] = 1;
        pows[2][1] = 2;
        pows[2][2] = 1;
        for (int i = 3; i < pows.length; i++) {
            pows[i][0] = 1;
            pows[i][i] = 1;
            for (int j = 1; j < i; j++) {
                pows[i][j] = pows[i - 1][j - 1] + pows[i - 1][j];
                pows[i][j] %= M2;
            }
        }
    }

    private static long sumOfPow(long to, int pow) {
        if (to == 1) {
            return 1;
        }

        Long vl = null;
        if (to < 1000) {
            vl = mods[pow].get(to);
        }

        if (vl != null) {
            return vl;
        }
        if (pow == 1) {
            long tx = to % M2;
            tx *= tx + 1;
            vl = tx % M2;
        } else {
            vl = sumOfPow1(to, pow) + sumOfPow2(to, pow);
            vl %= M2;
        }
        if (to < 1000) {
            mods[pow].put(to, vl);
        }

        return vl;
    }

    private static long sumOfPow1(long to, int pow) {
        return (pow(2, pow, M2) * sumOfPow(to / 2, pow)) % M2;
    }

    private static long sumOfPow2(long to, int pow) {
        if (to % 2 == 0) {
            return sumOfPow2(to - 1, pow);
        }
        if (to == 1) {
            return 1;
        }

        long sum = to / 2 + 1;
        sum %= M2;
        sum += sumOfPow1(to, pow);
        sum %= M2;
        for (int i = 1; i < pow; i++) {
            sum += (pows[pow][i] * sumOfPow1(to, pow - i)) % M2;
            sum %= M2;
        }

        return sum;
    }

    private static final class LogTreePar {

        private final int[] levels;
        private final int[][] parents;

        public LogTreePar(int n) {
            levels = new int[n];
            parents = new int[n][19];
            Arrays.fill(levels, -1);
            for (int[] x : parents) {
                Arrays.fill(x, -1);
            }
        }

        public boolean ispar(int f, int l) {
            if (levels[f] >= levels[l]) return false;
            int diff = levels[l] - levels[f];
            return up(l, diff) == f;
        }

        private int up(int item, int diff) {
            int r = 0;
            while (diff > 0 && item >= 0) {
                if (isset(diff, r)) {
                    diff ^= 1 << r;
                    item = parents[item][r];
                }
                r++;
            }
            return item;
        }

        public void add(int item, int parent) {
            parents[item][0] = parent;
            clt(item);
        }

        protected void clt(int item) {
            levels[item] = levels[parents[item][0]] + 1;
            for (int l = 1; l < 19; l++) {
                if (parents[item][l - 1] == -1) break;
                parents[item][l] = parents[parents[item][l - 1]][l - 1];
            }
        }

        public int lca(int f, int l) {
            if (levels[f] > levels[l]) {
                return lca(l, f);
            }
            return lca1(f, up(l, levels[l] - levels[f]));
        }

        private int lca1(int f1, int f2) {
            for (int r = 18; r >= 0 && f1 != f2; r--) {
                if (parents[f1][r] != parents[f2][r]) {
                    f1 = parents[f1][r];
                    f2 = parents[f2][r];
                }
            }
            return f1 == f2 ? f1 : parents[f1][0];
        }
    }

    private static class P {
        private boolean b;
        private final int ind;
        private final int parent;

        public P(int i, boolean b, int par) {
            this.ind = i;
            this.b = b;
            this.parent = par;

        }
    }

    private static void dfs(int start, int[][] neig, Consumer<int[]> onAdd, Consumer<int[]> onRemove) {
        ArrayList<P> toVisit = new ArrayList<P>(3000);
        toVisit.add(new P(start, true, -1));
        boolean[] vis = new boolean[neig.length];
        vis[start] = true;
        int[] level = new int[neig.length];
        while (toVisit.size() > 0) {
            P ppr = toVisit.remove(toVisit.size() - 1);
            if (!ppr.b) {
                onRemove.accept(new int[]{ppr.ind, level[ppr.ind], ppr.parent});
                continue;
            }
            ppr.b = false;
            int i = ppr.ind;
            toVisit.add(ppr);
            onAdd.accept(new int[]{ppr.ind, level[ppr.ind], ppr.parent});
            for (int kk : neig[i]) {
                if (!vis[kk]) {
                    vis[kk] = true;
                    level[kk] = level[i] + 1;
                    toVisit.add(new P(kk, true, i));
                }
            }
        }

    }

    private static int[][] tr(int n) {
        int[][] x = new int[2][n - 1];
        for (int i = 0; i < n - 1; i++) {
            x[0][i] = sc.nextInt() - 1;
            x[1][i] = sc.nextInt() - 1;
        }
        return pn(x, n);
    }

    private static int[][] pn(int[][] x, int n) {
        int[] ct = new int[n];
        int[][] res = new int[n][];
        for (int v : x[0]) {
            ct[v]++;
        }
        for (int v : x[1]) {
            ct[v]++;
        }
        for (int l = 0; l < n; l++) {
            res[l] = new int[ct[l]];
        }
        for (int i = 0; i < x[0].length; i++) {
            res[x[0][i]][--ct[x[0][i]]] = x[1][i];
            res[x[1][i]][--ct[x[1][i]]] = x[0][i];
        }
        return res;
    }

    private static boolean isset(long i, int k) {
        return (i & (1 << k)) > 0;
    }

    private static void solveT() throws IOException {
        int t = sc.nextInt();
        while (t-- > 0) {
            solve();
        }
    }

    private static long gcd(long l, long l1) {
        if (l > l1) return gcd(l1, l);
        if (l == 0) return l1;
        return gcd(l1 % l, l);
    }

    private static long pow(long a, long b, long m) {
        if (b == 0) return 1;
        if (b == 1) return a;
        long pp = pow(a, b / 2, m);
        pp *= pp;
        pp %= m;
        return (pp * (b % 2 == 0 ? 1 : a)) % m;
    }

    static class MyScanner {
        BufferedReader br;
        StringTokenizer st;

        MyScanner(BufferedReader br) {
            this.br = br;
        }

        public MyScanner(InputStream in) {
            this(new BufferedReader(new InputStreamReader(in)));
        }

        void findToken() {
            while (st == null || !st.hasMoreTokens()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }

        String next() {
            findToken();
            return st.nextToken();
        }

        Integer[] nab(int n) {
            Integer[] k = new Integer[n];
            for (int i = 0; i < n; i++) {
                k[i] = sc.fi();
            }
            return k;
        }

        int[] na(int n) {
            int[] k = new int[n];
            for (int i = 0; i < n; i++) {
                k[i] = sc.fi();
            }
            return k;
        }

        long[] nl(int n) {
            long[] k = new long[n];
            for (int i = 0; i < n; i++) {
                k[i] = sc.nextLong();
            }
            return k;
        }

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

        int fi() {
            String t = next();
            int cur = 0;
            boolean n = t.charAt(0) == '-';
            for (int a = n ? 1 : 0; a < t.length(); a++) {
                cur = cur * 10 + t.charAt(a) - '0';
            }
            return n ? -cur : cur;
        }

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

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

}

#include <bits/stdc++.h>
using namespace std;
const long double EPS = 1e-9, PI = acos(-1.);
const int INF = 0x3f3f3f3f, MOD = 1e9 + 7;
const int N = 1e3 + 5, M = 1e6 + 5;
int n, a[N];
vector<int> v;
int main() {
  scanf("%d", &n);
  int ok = 1;
  for (int i = 0; i < n; i++) {
    scanf("%d", &a[i]);
    ok = ok && (a[i] % a[0] == 0);
  }
  if (ok) {
    printf("%d\n", 2 * n + 1);
    for (int i = 0; i < n; i++) printf("%d %d ", a[0], a[i]);
    printf("%d\n", a[0]);
  } else
    printf("-1\n");
  return 0;
}


x = input()
y = input()
z = ''
for i in range(len(x)):
    if x[i] < y[i]:
        print("-1")
        exit(0)
    else:
        z = z + y[i]
print(z)

niwel vkvkkv -1 -1 aa eodnlemiicdedmkcgavqbnqmm ftrd zzz

//package javaapplication1;
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
import java.io.*;
import java.util.*;
public class Main {
    public static void main(String[] args) throws IOException{
        //BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        PrintWriter pw=new PrintWriter(new PrintStream(System.out));
        //Scanner sc=new Scanner(System.in);
        FastScanner in=new FastScanner();
        String x=in.nextToken();
        String z=in.nextToken();
        char [] ans=new char[x.length()];
        for (int i = 0; i < x.length(); ++i) {
            if(z.charAt(i)<x.charAt(i))
                ans[i]=z.charAt(i);
            else if(z.charAt(i)>x.charAt(i)){pw.println(-1);pw.flush();System.exit(0);}
            else
                ans[i]=x.charAt(i);
         }
        pw.println(String.valueOf(ans));pw.flush();
    }
    public static class FastScanner
	{
		BufferedReader br;
		StringTokenizer st;

		public FastScanner(String s)
		{
			try {
				br = new BufferedReader(new FileReader(s));
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

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

		String nextToken()
		{
			while (st == null || !st.hasMoreElements())
			{
				try {
					st = new StringTokenizer(br.readLine());
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			return st.nextToken();
		}

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

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

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

		String next()
		{
			return nextToken();
		}
	}
 }


def PolandBall(n, k):
    # condiciones que no cumplen con los requisitos
    if n < 4 or k > 3 or k == 1 or (k == 2 and n == 4):
        print('-1')
        return

    # si k=2
    if k == 2:
        print(n-1)
        for i in range(1, n):
            print(str(i)+' '+str(i+1))
        return

    # si k=3 y n=4
    if n == 4:
        print(n-1)
        print('1 2')
        print('2 3')
        print('3 4')
        return

     # si k=3 y n>4
    print(n)
    print('1 2')
    print('2 3')
    print('1 4')
    print('3 5')
    for i in range(5, n+1):
        print('1 '+str(i))

n, k = map(int, input().split())
PolandBall(n, k)

# Casos de prueba:
# 4 1  ##respuesta -1
# 5 2  ##respuesta  4

# 2 1        ##respuesta -1
# 2 3        ##respuesta -1
# 3 3        ##respuesta -1

# 4 2        ##respuesta -1
# 7 2        ##respuesta 6
# 100 2      ##respuesta 99
# 500 2      ##respuesta 499
# 1000 2     ##respuesta 999

# 4 3        ##respuesta 3
# 7 3        ##respuesta 7
# 100 3      ##respuesta 100
# 500 3      ##respuesta 500
# 1000 3     ##respuesta 1000

# 1000 1000  ##respuesta -1

import java.io.IOException;

public class Test {

    int readInt() {
        int ans = 0;
        try {
            boolean start = false;
            for (int c = 0; (c = System.in.read()) != -1; ) {
                if (c >= '0' && c <= '9') {
                    start = true;
                    ans = ans * 10 + c - '0';
                } else if (start) break;
            }
        } catch (IOException e) {
        }
        return ans;
    }

    void start() {
        int n = readInt(), k = readInt();
        while(true) {
            if (k == 1) break;
            if (k == 2) {
                if (n <= 4) break;

                System.out.println(4 + (n - 4) * 2);
                int[][] es = {
                        {1, 2},
                        {2, 3},
                        {2, 4},
                        {3, 4}
                };
                for (int[] e : es)
                    System.out.println(e[0] + " " + e[1]);
                for (int i = 5; i <= n; i++) {
                    System.out.println(1 + " " + i);
                    System.out.println(3 + " " + i);
                }
                return;
            }
            if (k == 3) {
                if (n <= 3) break;
                System.out.println(n - 1);
                int[][] es = {
                        {1, 2},
                        {2, 3},
                        {3, 4}
                };
                for (int[] e : es)
                    System.out.println(e[0] + " " + e[1]);
                for (int i = 5; i <= n; i++)
                    System.out.println(2 + " " + i);
                return;
            }
            break;
        }
        System.out.println(-1);
    }

    public static void main(String[] args) {
        new Test().start();
    }
}


#include <bits/stdc++.h>
using namespace std;
const int maxn = 200050;
int n, m, k, mx;
int a[maxn], ans;
int l, r, fa[maxn], siz[maxn];
vector<int> G[maxn];
map<int, int> mp;
int f(int x) { return fa[x] == x ? x : fa[x] = f(fa[x]); }
int main() {
  scanf("%d%d%d", &n, &m, &k);
  for (int i = 1; i <= n; ++i) scanf("%d", &a[i]), fa[i] = i;
  for (int i = 1; i <= m; ++i) {
    scanf("%d%d", &l, &r);
    if (f(l) != f(r)) fa[f(l)] = f(r);
  }
  for (int i = 1; i <= n; ++i) siz[f(i)]++, G[f(i)].push_back(a[i]);
  for (int i = 1; i <= n; ++i)
    if (siz[i]) {
      mp.clear();
      mx = 0;
      for (int j = 0; j <= G[i].size() - 1; ++j)
        mp[G[i][j]]++, mx = max(mx, mp[G[i][j]]);
      ans += siz[i] - mx;
    }
  printf("%d", ans);
  return 0;
}

from collections import defaultdict, deque
from sys import stdin, stdout

def dfs(visited, node_idx, graph, color_count, sock_colors):
    visited[node_idx] = True
    color_count[sock_colors[node_idx]] += 1
    count = 1
    for nbor_idx in graph[node_idx]:
        if not visited[nbor_idx]:
            count += dfs(visited, nbor_idx, graph, color_count, sock_colors)
    return count

def bfs(visited, idx, graph, color_count, sock_counts):
    q = deque()
    q.append(idx)
    count = 0
    while len(q) != 0:
        _next = q.popleft()
        if visited[_next]:
            continue
        visited[_next] = True
        color_count[sock_colors[_next]] += 1
        count += 1
        for nbor_idx in graph[_next]:
            q.append(nbor_idx)

    return count

def disjoint(graph, sock_colors):
    total = 0
    visited = [False] * len(graph)
    for idx, nbors in enumerate(graph):
        color_count = defaultdict(int)
        if not visited[idx]:
            size = bfs(visited, idx, graph, color_count, sock_colors)
            total += size - max(color_count.values())

    return total

if __name__ == '__main__':
    num_socks, num_days, num_colors = list(map(int, stdin.readline().split(' ')))
    sock_colors = list(map(int, stdin.readline().split(' ')))
    graph = [[] for i in range(num_socks)]

    for i in range(num_days):
        a, b = list(map(int, stdin.readline().split(' ')))
        a -= 1
        b -= 1
        graph[a].append(b)
        graph[b].append(a)

    ans = disjoint(graph, sock_colors)
    print(ans)


n=int(input())

a=input().split()

b=input().split()

a.remove('0')

b.remove('0')

k=a.index(b[0])

a=a[k:]+a[:k]

if a==b:

    print('YES')

else:

    print('NO')

# Made By Mostafa_Khaled

YES YES YES YES YES NO YES YES YES NO YES YES NO NO NO NO YES YES YES YES NO YES NO NO YES YES YES YES YES YES YES YES YES YES NO NO YES NO YES NO NO YES YES YES YES NO YES NO YES YES

#include <bits/stdc++.h>
using namespace std;
map<int, int> a;
int b[200005];
int main() {
  int n, x;
  scanf("%d", &n);
  int j = 0;
  for (int i = 0; i < n; i++) {
    scanf("%d", &x);
    if (x > 0) a[x] = j++;
  }
  int flag = 1, temp, k = 0;
  scanf("%d", &x);
  temp = (a[x] + 1) % j;
  for (int i = 1; i < n; i++) {
    scanf("%d", &x);
    if (x > 0) {
      if (temp != a[x]) flag = 0;
      temp = (a[x] + 1) % j;
      b[k++] = x;
    }
  }
  if (!flag) {
    for (int i = 0; i < k; i++) {
      if (a[b[i]] != i)
        break;
      else if (i == k - 1 && a[b[i]] == i)
        flag = 1;
    }
  }
  if (flag)
    cout << "YES" << endl;
  else
    cout << "NO" << endl;
  return 0;
}


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

public class Main {

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

        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder out = new StringBuilder();
        StringTokenizer tk;

        char[] a = in.readLine().toCharArray();
        char[] b = in.readLine().toCharArray();

        int i = 0, lenA = a.length;
        while(a[i] == '0' && i < (lenA - 1))
            ++i;

        int d = 0, lenB = b.length;
        while(b[d] == '0' && d < (lenB - 1))
            ++d;

        if((lenA - i) > (lenB - d))
            System.out.println(">");
        else if((lenA - i) < (lenB - d))
            System.out.println("<");
        else {

            for (int j = 0; j < (lenA - i); j++) {
                if(a[j + i] > b[j + d]) {
                    System.out.println(">");
                    return;
                }else if(a[j + i] < b[j + d]) {
                    System.out.println("<");
                    return;
                }
            }
            System.out.println("=");
        }
    }
}

a = input()
b = input()
if len(a)>len(b):
    gap = len(a)-len(b)
    new = ''
    for _ in range(gap):
        new+='0'
    b = new + b
elif len(b)>len(a):
    gap = len(b) - len(a)
    new = ''
    for _ in range(gap):
        new+='0'
    a = new + a
for i in range(0,len(a)):
    if(a[i]>b[i]):
        print('>')
        exit()
    elif(b[i]>a[i]):
        print('<')
        exit()
print('=')


import java.util.*;
import java.io.*;
import java.math.*;
public class Main {

    PrintWriter out = new PrintWriter(System.out);
    InputReader ir = new InputReader(System.in);
    final long kmod = 993960000099397l;
    int arr[];
    int hash[];
    void solve() throws IOException{
        int n = ir.readInt();
        int k = ir.readInt();
        hash = new int[2200001];
        arr = new int[n];
        int min = Integer.MAX_VALUE;
        for(int i = 0; i < n; i++) {
            arr[i] = ir.readInt();
            hash[arr[i]] = 1;
            min = Math.min(min, arr[i]);
        }
        for(int i = 2; i <= 2200000; i++) {
            hash[i] += hash[i - 1];
        }

        for(int i = min; i >= 1; i--) {
            if(check(i, k)) {
                out.println(i);
                return;
            }
        }

    }

    boolean check(int num, int k) {
        if(num <= k)
            return true;

        int prev = 0;
        for(int i = num; i <= 2200000; i += num) {
            if(hash[i - 1] - hash[prev + k] != 0) {
                return false;
            }
            prev = i;
        }
        return true;
    }

    void run() throws IOException{
        solve();
        out.close();
    }
    public static void main(String args[]) throws IOException{
        new Main().run();
    }
}
class InputReader {

    private InputStream stream;
    private byte[] buf = new byte[1024];
    private int curChar;
    private int numChars;
    private SpaceCharFilter filter;

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

    public int read() {
        if (numChars == -1)
            throw new InputMismatchException();
        if (curChar >= numChars) {
            curChar = 0;
            try {
                numChars = stream.read(buf);
            } catch (IOException e) {
                throw new InputMismatchException();
            }
            if (numChars <= 0)
                return -1;
        }
        return buf[curChar++];
    }
    public final int readInt() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
    }
    public long readLong() {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        int sgn = 1;
        if (c == '-') {
            sgn = -1;
            c = read();
        }
        long res = 0;
        do {
            if (c < '0' || c > '9')
                throw new InputMismatchException();
            res *= 10;
            res += c - '0';
            c = read();
        } while (!isSpaceChar(c));
        return res * sgn;
    }

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

    public boolean isSpaceChar(int c) {
        if (filter != null)
            return filter.isSpaceChar(c);
        return isWhitespace(c);
    }
        public double readDouble() {
        return Double.parseDouble(readString());
    }

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

    public String next() {
        return readString();
    }

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

#include <bits/stdc++.h>
using namespace std;
const int maxn = 300050;
const int maxv = 1000050 * 2;
int n, k, a[maxn], mp[maxv], p[maxv];
inline int read() {
  int x = 0, f = 1;
  char ch = getchar();
  while (!isdigit(ch)) {
    if (ch == '-') f = -1;
    ch = getchar();
  }
  while (isdigit(ch)) {
    x = x * 10 + ch - '0';
    ch = getchar();
  }
  return x * f;
}
int main() {
  n = read();
  k = read();
  int a, t = 10000000;
  for (int i = 1; i <= n; ++i) mp[a = read()]++, t = min(t, a);
  for (int i = 1; i <= maxv; ++i) mp[i] += mp[i - 1];
  for (int i = 1; i <= maxv; ++i) p[i] = mp[min(maxv, i + k)] - mp[i - 1];
  int ans = min(t, k);
  for (int i = k + 1; i <= t; ++i) {
    int j = i;
    int tmp = 0;
    while (j <= maxv) {
      tmp += p[j];
      j = j + i;
    }
    if (tmp == n) ans = i;
  }
  printf("%d\n", ans);
  return 0;
}


import java.util.*;

public class Main {

	public static void main(String[] args) {

		Scanner stdin = new Scanner(System.in);

		String contest = stdin.next();
		String arrange = stdin.next();
		int[] dateC = makeDate(contest);
		int[] dateBob = makeDate(arrange);
		boolean age = false;
		for (int i=0; i<6; i++) {
			int[] newDate = new int[3];
			newDate[0] = dateBob[i/2]; 			  				  // 0, 0, 1, 1, 2, 2
			if (i < 3)
				newDate[1] = dateBob[(i+1)%3];                    // 1, 2, 0, 2, 0, 1
			else
				newDate[1] = dateBob[(i+2)%3];
			if (i ==0 || i== 5)									  // 2, 1, 2, 0, 1, 0
				newDate[2] = dateBob[2-i%3];
			else
				newDate[2] = dateBob[i%3];

			if (isValid(newDate)) {
				if (old(newDate, dateC))
					age = true;
			}

			//System.out.println(newDate[0]+" "+newDate[1]+" "+newDate[2]);
		}

		if (age)
			System.out.println("YES");
		else
			System.out.println("NO");

	}

	public static int[] makeDate(String d) {
		int[] date = new int[3];
		date[0] = (d.charAt(0) - '0')*10 + (d.charAt(1) - '0');
		date[1] = (d.charAt(3) - '0')*10 + (d.charAt(4) - '0');
		date[2] = (d.charAt(6) - '0')*10 + (d.charAt(7) - '0');
		return date;
	}

	public static boolean isValid(int[] d) {

		int[] daysreg = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
		int[] daysleap = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

		if (d[2]%4 == 0) {
			if (d[1] <= 12 && d[0] <= daysleap[d[1]-1])
				return true;
			else
				return false;
		}
		else {
			if (d[1] <= 12 && d[0] <= daysreg[d[1]-1])
				return true;
			else
				return false;
		}
	}

	public static boolean old(int[] d1, int[] d2) {
		// by year
		int age = d2[2] - d1[2];

		if (d2[1] < d1[1])
			age--;
		else if (d2[1] == d1[1] && d2[0] < d1[0] )
			age--;

		return (age >= 18);
	}
}


#include <bits/stdc++.h>
using namespace std;
void USACO(string s) {
  freopen((s + ".in").c_str(), "r", stdin);
  freopen((s + ".out").c_str(), "w", stdout);
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  int n, s, t;
  cin >> n >> s >> t;
  s--, t--;
  int a[n];
  for (int i = 0; i < n; ++i) {
    cin >> a[i];
    a[i]--;
  }
  for (int k = 0; k < n; ++k) {
    if (s == t) {
      cout << k << "\n";
      return 0;
    }
    s = a[s];
  }
  cout << -1 << "\n";
}

import java.util.*;

public class Main {
  public static void main(String[] strings) {
    Scanner scan = new Scanner(System.in);
    int n = scan.nextInt();
    int s = scan.nextInt() - 1;
    int t = scan.nextInt() - 1;
    int[] p = new int[n];
    for (int i = 0; i < p.length; ++i) {
      p[i] = scan.nextInt() - 1;
    }
    boolean[] used = new boolean[n];
    int res = 0;
    for (int i = s; !used[i]; i = p[i], ++res) {
      used[i] = true;
      if (i == t) {
        System.out.println(res);
        return;
      }
    }
    System.out.println(-1);
    scan.close();
  }
}


#include <bits/stdc++.h>
using namespace std;
const double eps = 1e-5;
const int inf = (1 << 31) - 1;
const int hinf = 1000000000;
const int mod = 1000000007;
int main() {
  double e = 1;
  int n;
  cin >> n;
  double p;
  double ans = 0;
  for (int i = 1; i <= n; i++) {
    scanf("%lf", &p);
    ans += e * p;
    e = 1 + (1 + e) * p;
  }
  printf("%.15lf\n", ans);
}

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

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

class TaskD {
	public void solve(int testNumber, InputReader in, PrintWriter out) {
        int n = in.readInt();
        double[] p = new double[n];
        for (int i = 0; i < n; ++i)
            p[i] = in.readDouble();
        double res = 0.0;
        double exLen = 0.0;
        for (int i = 0; i < n; ++i) {
            res += p[i] * (1 + 2 * exLen);
            exLen = p[i] * (1 + exLen);
        }
        out.printf("%.8f\n", res);
	}
}

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

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

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

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

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

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

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


n, a, b=map(int, input().split())
l=list(map(int, input().split()))
l.sort()
print(l[-a]-l[-a-1])

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

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

    String inputs[] = in.nextLine().split(" ");
    int total = Integer.parseInt(inputs[0]);
    int petsyaChoresNumber = Integer.parseInt(inputs[1]);
    int vasyaChoresNumber = Integer.parseInt(inputs[2]);
    int[] complexities = Arrays.stream(in.nextLine().split(" ")).mapToInt(Integer::parseInt).toArray();
    Arrays.sort(complexities);

    out.print(complexities[vasyaChoresNumber] - complexities[vasyaChoresNumber - 1]);
  }
}