import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.ObjectInputStream.GetField;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Random;
import java.util.Scanner;
import java.util.Stack;
import java.util.TreeMap;
import java.util.TreeSet;

		public	class Q2 {

				static long MOD = 1000000007;
				static boolean b1,b[],bc[];
				static boolean boo[][][];
				static int ans1 = -1,ans2 = -1, root;
				static ArrayList<Integer>[] amp,amp1;
				static ArrayList<Pair>[] pmp;
				static int sum[],dist[],cnt[],ans[],size[],col[][];
				static int p = 0,cnt1 =0 ,cnt2 = 0;
				//static ArrayList<Pair3>[][][] pmp;
				static FasterScanner sc = new FasterScanner(System.in);
				static Queue<Integer> q = new LinkedList<>();
				static int arr[],start[],end[],color[],parent[];
				static PriorityQueue<Integer> pq;
				//static ArrayList<Integer> parent = new ArrayList<>();
				static LinkedList<Integer> fa;
				static BufferedWriter log;
				static TreeMap<Integer,Integer> tm = new TreeMap<>();
			//	static HashMap<Integer,Pair> hs;
				static Stack<Integer> stack = new Stack<>();
				static Pair prr[];
				static int dp[][];
				static long parent1[],parent2[],size1[],size2[],value[];
				static long Ans;
				public static void main(String[] args) throws Exception {
					/*new Thread(null, new Runnable() {
						public void run() {
							try {
								soln();
							} catch (Exception e) {
								System.out.println(e);
							}
						}
					}, "1", 1 << 26).start();*/
					soln();
			    }
				static int MAX = 1000005;
				static int n , m ,k, max, x1, x2;
				static HashSet<Pair> hs;
				static double DP[][][];
				public static void soln() throws IOException {
					//FasterScanner in = new FasterScanner(new FileInputStream("C:\\Users\\Admin\\Desktop\\QAL.txt"));
					//PrintWriter out = new PrintWriter("C:\\Users\\Admin\\Desktop\\A1.txt");
					log = new BufferedWriter(new OutputStreamWriter(System.out));
					int n = sc.nextInt();
					int m[] = sc.nextIntArray(n);
					int r[] = sc.nextIntArray(n);
					boolean b[] = new boolean[1000000];
					long lcm = m[0], gcd = m[0], mul =m[0];
					for(int i =1 ;i <n; i++){
						lcm = ((lcm*m[i])/gcd(lcm,m[i]));
					}
					//System.out.println(mul+" "+lcm);
					int cnt = 0;
					for(int i = 0; i<n ; i++){
						for(int j = 1;j<=lcm;j++){
							if(j%m[i]==r[i] && !b[j]){
								b[j] = true;
								cnt++;
							}
						}
					}
					//System.out.println(cnt);
					System.out.printf("%.9f",(double)cnt/lcm);
					log.close();
					//out.close();
				}
				 static long maxSubArraySum(long a[])
				    {
				        int size = a.length;
				        long max_so_far = Long.MIN_VALUE/2, max_ending_here = 0;

				        for (int i = 0; i < size; i++)
				        {
				            max_ending_here = max_ending_here + a[i];
				            if(max_so_far < max_ending_here)
				                max_so_far = max_ending_here;
				            if(max_ending_here < 0)
				                max_ending_here = 0;
				        }
				        return max_so_far;
				    }
				public class TrieNode{
					TrieNode[] t = new TrieNode[2];
					int cnt = 0;
				}
				public class Trie{
					TrieNode root;
					Trie(){
						root = new TrieNode();
					}
					public void insert(String s){
						TrieNode temp = root;
						for(int i = 0; i< s.length();i++){
							if(temp.t[s.charAt(i)-'0']==null){
								TrieNode n = new TrieNode();
								temp.t[s.charAt(i)-'0'] = n;
							}
							temp = temp.t[s.charAt(i)-'0'];
						}
						temp.cnt++;
					}
					public void delete(String s, TrieNode temp){

					}
					public String get(String s){
						StringBuilder sb = new StringBuilder();
						TrieNode temp = root;
						for(int i = 0; i< s.length();i++){
							int x = (s.charAt(i)-'0'+1)%2;
							if(temp.t[x]!=null){
								temp = temp.t[x];
								sb.append(1);
							}
							else{
								temp = temp.t[(x+1)%2];
								sb.append(0);
							}
						}
						return sb.toString();
					}
				}
				public static class FenwickTree {
				    int[] array; // 1-indexed array, In this array We save cumulative information to perform efficient range queries and updates
				    public FenwickTree(int size) {
				        array = new int[size + 1];
				    }
				    public int rsq(int ind) {
				        assert ind > 0;
				        int sum = 0;
				        while (ind > 0) {
				            sum += array[ind];ind -= ind & (-ind);
				        }
				        return sum;
				    }
				    public int rsq(int a, int b) {
				        assert b >= a && a > 0 && b > 0;
				        return rsq(b) - rsq(a - 1);
				    }
				    public void update(int ind, int value) {
				        assert ind > 0;
				        while (ind < array.length) {
				            array[ind] += value; ind += ind & (-ind);
				        }
				    }
				    public int size() {
				        return array.length - 1;
				    }
				}
				public static void dfs(int x){
					b[x] = true;
					for(int e:amp[x]){
						if(!b[e]){
							dfs(e);
						}
					}
				}
				public static void bfs(int x){
					b[x] = true;
					q = new LinkedList<Integer>();
					q.add(x);
					while(!q.isEmpty()){
						//System.out.println(q);
						int y = q.poll();
							for(int i:amp[y]){
							if(!b[i]){
								q.add(i);
								dist[i] = Math.max(dist[i], dist[y]+1);
								if(dist[i]>max){
									max = dist[i];
									k = i;
								}
								b[i]= true;
							}
						}
					}
				}
				static class Pair implements Comparable<Pair> {
					int u;
					int v;
					public Pair(){
						u = 0;
						v = 0;
					}
					public Pair(int u, int v) {
						this.u = u;
						this.v = v;
					}
					public int hashCode() {
						int hu = (int) (u ^ (u >>> 32));
						int hv = (int) (v ^ (v >>> 32));
						return 31*hu + hv;
					}

					public boolean equals(Object o) {
						Pair other = (Pair) o;
						return (u == other.u && v == other.v);
					}

					public int compareTo(Pair other) {
						return Long.compare(u, other.u) != 0 ? (Long.compare(u, other.u)) : (Long.compare(v, other.v));
					}

					public String toString() {
						return "[u=" + u + ", v=" + v + "]";
					}
				}

				public static long gcd(long gc, long m){
					if(m!=0) return gcd(m,gc%m);
					else return gc;
				}

				static int CeilIndex(int A[], int l, int r, int key)
			    {
			        while (r - l > 1)
			        {
			            int m = l + (r - l)/2;
			            if (A[m]>=key)
			                r = m;
			            else
			                l = m;
			        }

			        return r;
			    }
			/*	public static Pair recur(int N, int K, int C){
					if(K>k) return new Pair(Long.MAX_VALUE/2,-1);
					if(N>=n && k<K) return new Pair(Long.MAX_VALUE/2,-1);
					if(N>=n && k==K) return new Pair(0,k);
					if(N>=n) return new Pair(0,0);
					if(dp[N][C][K]!=null){
						//System.out.println(dp[N][C][K]);
						return dp[N][C][K];
					}
					Pair ans = new Pair(Long.MAX_VALUE/2,-1);
					if(arr[N]>0){
						Pair p;
						if(arr[N]==C) p = recur(N+1,K,arr[N]);
						else p = recur(N+1,K+1,arr[N]);
						if((p.u)<ans.u){
							ans = p;
						}
						if(p.u==ans.u){
							if(p.v>ans.v){
								ans = p;
							}
						}
					}
					else{
					for(int i = 1 ;i <= m; i++){
						Pair p;
						if(i==C)
						p = recur(N+1,K,i);
						else p = recur(N+1,K+1,i);
						p.u+=col[N][i-1];
						if((p.u)<ans.u){
							ans = p;
						}
						if(p.u==ans.u){
							if(p.v>ans.v){
								ans = p;
							}
						}
					}
					//System.out.println(ans);
					}
					return dp[N][C][K] = ans;
				}*/
				public static void mergeSort(int[] arr2, int l ,int r){
					if((r-l)>=1){
						int mid = (l+r)/2;
						mergeSort(arr2,l,mid);
						mergeSort(arr2,mid+1,r);
						merge(arr2,l,r,mid);
						//System.out.println(Ans);
					}
				}
				public static void merge(int arr[], int l, int r, int mid){
					int n1 = (mid-l+1), n2 = (r-mid);
					int left[] = new int[n1];
					int right[] = new int[n2];
					for(int i =0 ;i<n1;i++) left[i] = arr[l+i];
					for(int i =0 ;i<n2;i++) right[i] = arr[mid+1+i];
					int i =0, j =0, k = l;
					while(i<n1 && j<n2){
						if(left[i]>right[j]){
							cnt[right[j]]+=(n1-i);
							arr[k++] = right[j++];
						}
						else{
							arr[k++] = left[i++];
						}
					}
					while(i<n1) arr[k++] = left[i++];
					while(j<n2) arr[k++] = right[j++];
				}
				public static void buildGraph(int n){
					for(int i =0;i<n;i++){
						int x = sc.nextInt(), y = sc.nextInt();
						amp[x].add(y);
						hs.add(new Pair(x,y));
						hs.add(new Pair(y,x));
					}
				}

				public static int getParent(int x){
					while(parent[x]!=x){
						parent[x] = parent[ parent[x]];
						x = parent[ x];
					}
					return x;
				}

				static int min(int a, int b, int c){
					if(a<b && a<c) return a;
					if(b<c) return b;
					return c;
				}
				private static void permutation(String prefix, String str) {
				    int n = str.length();
				    if (n == 0); //hs.add(prefix);
				    else {
				        for (int i = 0; i < n; i++)
				            permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i+1, n));
				    }
				}
				static class Graph{
					int vertex;
					long weight;
				}
				public static void buildTree(int n){
					int arr[] = sc.nextIntArray(n);
					for(int i = 0;i<n;i++){
						int x = arr[i]-1;
						amp[i+1].add(x);
						amp[x].add(i+1);
					}
				}
				static class Node{
					long max = 0, pre = 0, suf = 0, sum = 0;
					Node(long max, long pre, long suf, long sum){
						this.max = max;
						this.pre = pre;
						this.suf = suf;
						this.sum = sum;
					}
					Node(){};
				}
				static class SegmentTree {
					Node st[];
				//	long lazy[];
					SegmentTree(int n) {
						int size = 4 * n;
						st = new Node[size];
						for(int i = 0; i< size;i++) st[i] = new Node();
					//	lazy = new long[size];
						build(0, n - 1, 1);
					}
					Node comb(Node l,  Node r){
						long sum = l.sum+r.sum;
						long pre = Math.max(l.pre, l.sum+r.pre);
						long suf = Math.max(r.suf, r.sum+l.suf);
						long max = max(l.max, r.max, l.suf+r.pre);
						return new Node(max, pre , suf, sum);
					}
					Node build(int ss, int se, int si) {
						if(ss==se){
							st[si] = new Node(arr[ss],arr[ss],arr[ss],arr[ss]);
							return st[si];
						}
						int mid = (ss+se)/2;
						Node a1 = build(ss, mid, si*2), a2 = build(mid+1, se, si*2+1);
						return st[si] = comb(a1,a2);
					}

					void update(int si, int ss, int se, int idx, int val) {
						if (ss == se) {
							arr[ss] = val;
							st[si] = new Node(arr[ss],arr[ss],arr[ss],arr[ss]);
						}
						else {
							int mid = (ss + se) / 2;
							if(ss <= idx && idx <= mid)
					        {
					             update(2*si, ss, mid, idx, val);
					        }
					        else
					        { update(2*si+1, mid+1, se, idx, val);
					        }
							st[si] = comb(st[si*2],st[si*2+1]);
						}
					}
					Node get(int qs, int qe, int ss, int se, int si){
						if(qs>se || qe<ss){
							return new Node(-10000000,-100000000,-10000000,-100000000);
						}
						if (qs <= ss && qe >= se) {
							return st[si];
						}
						int mid = (ss+se)/2;
						Node temp1 = get(qs, qe, ss, mid, si * 2), temp2 = get(qs, qe, mid + 1, se, si * 2 + 1);
						return st[si] = comb(temp1,temp2);
					}
					/*void updateRange(int node, int start, int end, int l, int r, long val)
					{
					    if(lazy[node] != 0)
					    {
					        // This node needs to be updated
					        st[node] += (end - start + 1) * lazy[node];    // Update it
					        if(start != end)
					        {
					            lazy[node*2] += lazy[node];                  // Mark child as lazy
					            lazy[node*2+1] += lazy[node];                // Mark child as lazy
					        }
					        lazy[node] = 0;                                  // Reset it
					    }
					    if(start > end || start > r || end < l)              // Current segment is not within range [l, r]
					        return;
					    if(start >= l && end <= r)
					    {
					        // Segment is fully within range
					        st[node] += (end - start + 1) * val;
					        if(start != end)
					        {
					            // Not leaf node
					            lazy[node*2] += val;
					            lazy[node*2+1] += val;
					        }
					        return;
					    }
					    int mid = (start + end) / 2;
					    updateRange(node*2, start, mid, l, r, val);        // Updating left child
					    updateRange(node*2 + 1, mid + 1, end, l, r, val);   // Updating right child
					    st[node] = st[node*2] + st[node*2+1];        // Updating root with max value
					}

					long queryRange(int node, int start, int end, int l, int r)
					{
					    if(start > end || start > r || end < l)
					        return 0L;         // Out of range
					    if(lazy[node] != 0)
					    {
					        // This node needs to be updated
					        st[node] += (end - start + 1) * lazy[node];            // Update it
					        if(start != end)
					        {
					            lazy[node*2] += lazy[node];         // Mark child as lazy
					            lazy[node*2+1] += lazy[node];    // Mark child as lazy
					        }
					        lazy[node] = 0L;                 // Reset it
					    }
					    if(start >= l && end <= r)             // Current segment is totally within range [l, r]
					        return  st[node];
					    int mid = (start + end) / 2;
					    long p1 = queryRange(node*2, start, mid, l, r);         // Query left child
					    long p2 = queryRange(node*2 + 1, mid + 1, end, l, r); // Query right child
					    return (p1 + p2);
					}*/
					void print() {
						for (int i = 0; i < st.length; i++) {
							//System.out.print(st[i].u+" "+st[i].v+" "+st[i].z+"\n");
						}
						System.out.println();
					}
				}

				static class Tree {
					ArrayList<Integer>[] g ;
					int T[]; // parent
					int L[]; // level
					int P[][]; // P[i][j] = 2^j th parent of i

					public Tree(int n) {
						T = new int[n];
						L = new int[n];
						P = new int[n][log2(n) + 1];
						g = (ArrayList<Integer>[])new ArrayList[n];
						L[0] = 0;
						T[0] = -1;
						for (int i = 0; i < n; i++) {
							g[i] = new ArrayList<>();
						}
						for (int i = 0; i < n ; i++) {
							int a = sc.nextInt();
							for(int j = 0; j<a; j++){
								int b = sc.nextInt()-1;
								g[i].add(b);
								g[b].add(i);
							}
						}
						dfs(0, -1);
						for (int j = 0; (1 << j) <= n; j++)
							pre(0, j,-1);
					}

					public int log2(int n) {
						return (int) (Math.log10(n) / Math.log10(2));
					}

					public void dfs(int node, int p) {
						for (int k : g[node]) {
							if (k != p) {
								T[k] = node;
								L[k] = L[node] + 1;
								dfs(k, node);
							}
						}
					}
					public void pre(int node, int j,int p) {
						if (j == 0) {
							P[node][j] = T[node];
						} else {
							P[node][j] = P[P[node][j - 1]][j - 1];
						}
						for (int k : g[node]) {
							if(k!=p)
								pre(k, j,node);
						}
					}
					public int lca(int u, int v) {
						if (L[u] > L[v]) {
							int temp = u;
							u = v;
							v = temp;
						}
						int log;
						for (log = 0; (1 << log) <= L[v]; log++)
							; // convert level into log
						log--;

						for (int i = log; i >= 0; i--) {
							if ((1 << i) <= L[v] - L[u]) // make both node's level same
								v = P[v][i];
						}
						if (u == v)
							return u;
						for (int i = log; i >= 0; i--) {
							if (P[u][i] != -1 && P[u][i] != P[v][i]) // shift up both u and v
							{
								u = P[u][i];
								v = P[v][i];
							}
						}
						return T[u];
					}
				}
				public static long max(long x, long y, long z){
					if(x>=y && x>=z) return x;
					if(y>=x && y>=z) return y;
					return z;
				}

				public static void seive(long n){
					b = new boolean[(int) (n+1)];
					Arrays.fill(b, true);
					for(int i = 2;i*i<=n;i++){
						if(b[i]){
							for(int p = 2*i;p<=n;p+=i){
								b[p] = false;
							}
						}
					}
				}
				static long modInverse(long a, long mOD2){
				            return  power(a, mOD2-2, mOD2);
				}
				static long power(long x, long y, long m)
				{
				    if (y == 0)
				        return 1;
				    long p = power(x, y/2, m) % m;
				    p = (p * p) % m;

				    return (y%2 == 0)? p : (x * p) % m;
				}
				static long d,x,y;
				public static void extendedEuclidian(long a, long b){
					if(b == 0) {
				        d = a;
				        x = 1;
				        y = 0;
				    }
				    else {
				        extendedEuclidian(b, a%b);
				        int temp = (int) x;
				        x = y;
				        y = temp - (a/b)*y;
				    }
				}

				static class FasterScanner {

					private final InputStream stream;
					private final byte[] buf = new byte[8192];
					private int curChar, snumChars;
					private SpaceCharFilter filter;
					public int read() {
						if (snumChars == -1)
							throw new InputMismatchException();
						if (curChar >= snumChars) {
							curChar = 0;
							try {
								snumChars = System.in.read(buf);
							} catch (IOException e) {
								throw new InputMismatchException();
							}
							if (snumChars <= 0)
								return -1;
						}
						return buf[curChar++];
					}
					public FasterScanner(InputStream stream) {
						this.stream = stream;
					}
					public String nextString() {
						int c = read();
						while (isSpaceChar(c))
							c = read();
						StringBuilder res = new StringBuilder();
						do {
							res.appendCodePoint(c);
							c = read();
						} while (!isSpaceChar(c));
						return res.toString();
					}
					public int snext() {
						if (snumChars == -1)
							throw new InputMismatchException();
						if (curChar >= snumChars) {
							curChar = 0;
							try {
								snumChars = stream.read(buf);
							} catch (IOException e) {
								throw new InputMismatchException();
							}
							if (snumChars <= 0)
								return -1;
						}
						return buf[curChar++];
					}

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

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

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

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

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

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

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

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

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


import java.util.Scanner;

public class A {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in).useDelimiter("(:|\\s)+");
        scanner.nextInt();
        int ta = scanner.nextInt();
        int b = scanner.nextInt();
        int tb = scanner.nextInt();

        int hh = scanner.nextInt();
        int mm = scanner.nextInt();

        int sa = hh*60 + mm;
        int ea = sa + ta;

        int res = 0;
        for (int sb=5*60; sb <= 23*60 + 59; sb+= b) {
            int eb = sb + tb;

            if (eb > sa && ea > sb) res++;
        }
        System.out.print(res);

    }
}


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

public class B354 {
	public static void main(String [] args) throws IOException{
		double[][] g;
		int h;
		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer(bf.readLine());
		h = Integer.parseInt(st.nextToken());
		int sec = Integer.parseInt(st.nextToken());
//		int totCups = cups*(cups+1)/2;
		g = new double[12][12];
		g[1][1]=sec;
		int glasses=0;
		for(int i =1;i<=h;i++){
			for(int j =1;j<=i;j++){
				if(g[i][j]>1){
//					glasses++;
					g[i+1][j]+=(g[i][j]-1)/2;
					g[i+1][j+1]+=(g[i][j]-1)/2;
				}
				if(g[i][j]>=1)
					glasses++;
			}
		}

		System.out.println(glasses);

	}

}


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

public class MainD {
	static final StdIn in = new StdIn();
	static final PrintWriter out = new PrintWriter(System.out);

	public static void main(String[] args) {
		int n=in.nextInt(), w=in.nextInt();
		Pair[] ps = new Pair[n];
		for(int i=0; i<n; ++i)
			ps[i] = new Pair(in.nextInt(), in.nextInt());
//		List<Pair> p1 = new ArrayList<Pair>(), p2 = new ArrayList<Pair>();
//		for(int i=0; i<n; ++i) {
//			Pair p=new Pair(in.nextInt(), in.nextInt());
//			if(p.a<0)
//				p1.add(p);
//			else
//				p2.add(p);
//		}
//		int m=p2.size();
		Pair[] x = new Pair[n], y = new Pair[n];
		for(int i=0; i<n; ++i) {
//			x[i] = new Pair(p2.get(i).a, -(p2.get(i).b-w));
//			y[i] = new Pair(p2.get(i).a, -(p2.get(i).b+w));
			x[i] = new Pair(Math.abs(ps[i].a), Math.abs(ps[i].b-w));
			y[i] = new Pair(Math.abs(ps[i].a), Math.abs(ps[i].b+w));
		}
		Arrays.sort(x);
		Arrays.sort(y);
		List<Integer>[] toAdd = new List[n];
		for(int i=0; i<n; ++i)
			toAdd[i] = new ArrayList<Integer>();
		for(int i=0; i<n; ++i)
			toAdd[Arrays.binarySearch(y, new Pair(Math.abs(ps[i].a), Math.abs(ps[i].b+w)))]
					.add(Arrays.binarySearch(x, new Pair(Math.abs(ps[i].a), Math.abs(ps[i].b-w))));
		long ans=0;
		FenTree ft = new FenTree(n);
		for(int i=n-1; i>=0; --i) {
			Collections.sort(toAdd[i]);
			for(int ta : toAdd[i]) {
				ans+=ft.qry(ta+1);
				ft.upd(ta, 1);
			}
		}
		out.println(ans);
		out.close();
	}

	static class FenTree {
		int[] a;
		FenTree(int n) {
			a = new int[n+1];
		}
		void upd(int i, int x) {
			for(++i; i<a.length; i+=i&-i)
				a[i]+=x;
		}
		int qry(int i) {
			int r=0;
			for(; i>0; i-=i&-i)
				r+=a[i];
			return r;
		}
	}

	static class Pair implements Comparable<Pair> {
		int a, b;
		Pair(int a, int b) {
			this.a=a;
			this.b=b;
		}
		public int compareTo(Pair o) {
			return Double.compare((double)a/b, (double)o.a/o.b);
		}
	}

	static class StdIn {
		final private int BUFFER_SIZE = 1 << 16;
		private DataInputStream din;
		private byte[] buffer;
		private int bufferPointer, bytesRead;
		public StdIn() {
			din = new DataInputStream(System.in);
			buffer = new byte[BUFFER_SIZE];
			bufferPointer = bytesRead = 0;
		}
		public StdIn(InputStream in) {
			try{
				din = new DataInputStream(in);
			} catch(Exception e) {
				throw new RuntimeException();
			}
			buffer = new byte[BUFFER_SIZE];
			bufferPointer = bytesRead = 0;
		}
		public String next() {
			int c;
			while((c=read())!=-1&&(c==' '||c=='\n'||c=='\r'));
			StringBuilder s = new StringBuilder();
			while (c != -1)
			{
				if (c == ' ' || c == '\n'||c=='\r')
					break;
				s.append((char)c);
				c=read();
			}
			return s.toString();
		}
		public String nextLine() {
			int c;
			while((c=read())!=-1&&(c==' '||c=='\n'||c=='\r'));
			StringBuilder s = new StringBuilder();
			while (c != -1)
			{
				if (c == '\n'||c=='\r')
					break;
				s.append((char)c);
				c = read();
			}
			return s.toString();
		}
		public int nextInt() {
			int ret = 0;
			byte c = read();
			while (c <= ' ')
				c = read();
			boolean neg = (c == '-');
			if (neg)
				c = read();
			do
				ret = ret * 10 + c - '0';
			while ((c = read()) >= '0' && c <= '9');

			if (neg)
				return -ret;
			return ret;
		}
		public int[] readIntArray(int n, int os) {
			int[] ar = new int[n];
			for(int i=0; i<n; ++i)
				ar[i]=nextInt()+os;
			return ar;
		}
		public long nextLong() {
			long ret = 0;
			byte c = read();
			while (c <= ' ')
				c = read();
			boolean neg = (c == '-');
			if (neg)
				c = read();
			do
				ret = ret * 10 + c - '0';
			while ((c = read()) >= '0' && c <= '9');
			if (neg)
				return -ret;
			return ret;
		}
		public long[] readLongArray(int n, long os) {
			long[] ar = new long[n];
			for(int i=0; i<n; ++i)
				ar[i]=nextLong()+os;
			return ar;
		}
		public double nextDouble() {
			double ret = 0, div = 1;
			byte c = read();
			while (c <= ' ')
				c = read();
			boolean neg = (c == '-');
			if (neg)
				c = read();
			do
				ret = ret * 10 + c - '0';
			while ((c = read()) >= '0' && c <= '9');
			if (c == '.')
				while ((c = read()) >= '0' && c <= '9')
					ret += (c - '0') / (div *= 10);
			if (neg)
				return -ret;
			return ret;
		}
		private void fillBuffer() throws IOException {
			bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
			if (bytesRead == -1)
				buffer[0] = -1;
		}
		private byte read() {
			try{
				if (bufferPointer == bytesRead)
					fillBuffer();
				return buffer[bufferPointer++];
			} catch(IOException e) {
				throw new RuntimeException();
			}
		}
		public void close() throws IOException {
			if (din == null)
				return;
			din.close();
		}
	}
}


import java.util.Scanner;

public class FleaTravel {
    public static void main(String[] args) {
        int n;
        Scanner cin = new Scanner(System.in);
        n = cin.nextInt();
        boolean h[] = new boolean[n];
        for (int i = 0; i < n; i++) {
            h[i] = false;
        }
        int x = 0;
        h[x] = true;
        for (int k = 0; k < n; k++) {
            x += k;
            if (x >= n) {
                x -= n;
            }
            h[x] = true;
        }
        for (int i = 0; i < n; i++) {
            if (h[i] == false) {
                System.out.println("NO");
                System.exit(0);
            }
        }
        System.out.println("YES");
    }
}


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

public class CuttingBanner implements Closeable {

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

    public void solve() {
        char[] codeforces = "CODEFORCES".toCharArray();
        char[] word = in.next().toCharArray();
        int idx = 0, i = 0, j = 0, n = word.length;
        while (idx < Math.min(10, n)) {
            if (word[idx] == codeforces[j]) {
                j++;
            } else break;
            idx++;
        }
        idx = 0;
        while (idx < Math.min(10, n)) {
            if (word[word.length - idx - 1] == codeforces[9 - i]) {
                i++;
            } else break;
            idx++;
        }

        out.println((i + j >= 10) ? "YES" : "NO");
    }

    @Override
    public void close() throws IOException {
        in.close();
        out.close();
    }

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

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

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

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

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

        public void close() throws IOException {
            reader.close();
        }
    }

    public static void main(String[] args) throws IOException {
        try (CuttingBanner instance = new CuttingBanner()) {
            instance.solve();
        }
    }
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class NextRound {

    public static void main(String[] args) throws IOException {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        String []w=br.readLine().trim().split("\\s+");
        int n=Integer.parseInt(w[0]);
        int k=Integer.parseInt(w[1])-1;
        String []ww=br.readLine().trim().split("\\s+");
        int c=0;
        for (int i = 0; i < ww.length; i++) {
            if(Integer.parseInt(ww[i])>=Integer.parseInt(ww[k]) && Integer.parseInt(ww[i])>0 ){
                c++;
            }

        }
        System.out.print(c);

    }

}


import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;

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

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

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

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

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

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

	        String nextLine()
	        {
	            String str = "";
	            try
	            {
	                str = br.readLine();
	            }
	            catch (IOException e)
	            {
	                e.printStackTrace();
	            }
	            return str;
	        }
	    }
	 public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out));

  static int MAX = (int) 1e6;
    public static void main(String[] args) {

    	FastReader sc = new FastReader();
    	int a1 = sc.nextInt();
    	int a2 = sc.nextInt();
    	int k1 = sc.nextInt();
    	int k2 = sc.nextInt();
    	int n = sc.nextInt();
    	int min1 = Math.max(0,n-(k1-1)*a1 - (k2-1)*a2);
    	int min = Math.min(a1+a2,min1);
    	int max1 = 0;
    	if(k1 < k2) {
    	   max1+=Math.min(n/k1,a1);
    	   n-=k1*max1;
    	   if(n > 0) {
    		   max1+=Math.min(n/k2, a2);
    	   }
    	}else if(k2 < k1) {
    		max1+=Math.min(n/k2, a2);
    		n-=k2*max1;
    		if(n > 0) {
    			max1+=Math.min(n/k1, a1);
    		}
    	}else {
    		max1+=Math.min(n/k1, a1+a2);
    	}
    	out.print(min+" "+max1);
    	out.close();
    	}
}


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

public class Main {
    static long derangement[];
    static void build(int k) {
        derangement[0] = 1;
        derangement[1] = 0;
        for (int i = 2; i <= k; i++) derangement[i] = (i - 1) * (derangement[i - 1] + derangement[i - 2]);
    }
    static long combination(int n, int k) {
        switch (k) {
            case 0 : return 1;
            case 1: return n;
            case 2: return (long) n * (n - 1) / 2;
            case 3: return (long) n * (n - 1) * (n - 2) / 6;
            case 4: return (long) n * (n - 1) * (n - 2) * (n - 3) / 24;
            default: return -1;
        }
    }
    static void solve() throws IOException {
        rl(); int n = ni2(); int k = ni2();
        derangement = new long[k + 1];
        long res = 0;
        build(k);
        for (int i = 0; i <= k; i++) res += derangement[i] * combination(n, i);
        ans.append(res).append('\n');
        output.write(ans.toString());
        output.flush();
        output.close();
    }

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

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

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

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

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

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

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


import java.io.*;
import java.util.*;
public class code {
	static printer pw;
	static boolean[] visit;
	static ArrayList<Pair>[] adj;
	static ArrayList<Integer> list;
	static long max=01;
	static void dfs(int i, long c) {
		visit[i]=true;
		max=Math.max(c, max);
		for(Pair p: adj[i]) {
			if(!visit[p.x-1]) {
				dfs(p.x-1, c+1l*p.y);
			}
		}
	}
	static long Pow(long a, int e, int mod)
	{
		a %= mod;
		long res = 1;
		while (e > 0) {
			if ((e & 1) == 1)
				res = (res * a) % mod;
			a = (a * a) % mod;
			e >>= 1;
		}
		return res;
	}
	public static double dist(Pair a, Pair b) {
		return Math.sqrt((a.x-b.x)*(a.x-b.x)+ (a.y-b.y)*(a.y-b.y));
	}
	public static boolean sign(int x) {
		return x>0;
	}
	static int test(int[] arr, int mid) {
		int ans=0;
		for(int i=1; i<arr.length; i++) {
			if(arr[i]==-1 && arr[i-1]!=-1) {
				if(Math.abs(mid-arr[i-1])>Math.abs(ans))
					ans=mid-arr[i-1];
			}
			if(arr[i]!=-1 && arr[i-1]==-1) {
				if(Math.abs(mid-arr[i])>Math.abs(ans))
					ans=mid-arr[i];
			}
		}
		return ans;
	}
	public static void main(String[] args) throws Exception {
		Scanner sc= new Scanner(System.in);
		pw = new printer();
		int w1=sc.nextInt(),h1=sc.nextInt(),w2=sc.nextInt(),h2=sc.nextInt();
		long ans=1l*(w1-w2!=0?1:0)*h2+1l*(h1+h2+2)+1l*(w1==w2?h1+h2+2:h1+2)+2*1l*(w1);
		pw.println(ans);
		pw.close();
	}
	static class Scanner {
		StringTokenizer st;
		BufferedReader br;

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

		public Scanner(FileReader r) {
			br = new BufferedReader(r);
		}

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

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

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

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

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

		public int[] nextArr(int n) throws IOException {
			int[] arr = new int[n];
			for (int i = 0; i < arr.length; i++)
				arr[i] = nextInt();
			return arr;
		}
		public Integer[] nextsort(int n) throws IOException{
			Integer[] arr=new Integer[n];
			for(int i=0; i<n; i++)
				arr[i]=nextInt();
			return arr;
		}
		public boolean ready() throws IOException {
			return br.ready();
		}
	}
	static class printer{
		PrintWriter pw;
		public printer() {
			pw=new PrintWriter(System.out);
		}
		public void print(String s) throws IOException{
			pw.print(s);
		}
		public void print(int s) throws IOException{
			pw.print(s);
		}
		public void print(long s) throws IOException{
			pw.print(s);
		}
		public void print(char s) throws IOException{
			pw.print(s);
		}
		public void print(Integer s) throws IOException{
			pw.print(s);
		}
		public void print(Long s) throws IOException{
			pw.print(s);
		}
		public void print(Character s) throws IOException{
			pw.print(s);
		}
		public void println(String s) throws IOException{
			pw.println(s);
		}
		public void println(int s) throws IOException{
			pw.println(s);
		}
		public void println(long s) throws IOException{
			pw.println(s);
		}
		public void println(char s) throws IOException{
			pw.println(s);
		}
		public void println(Integer s) throws IOException{
			pw.println(s);
		}
		public void println(Long s) throws IOException{
			pw.println(s);
		}
		public void println(Character s) throws IOException{
			pw.println(s);
		}
		public void println(int[] arr) throws IOException{
			for(int i=0; i<arr.length-1; i++)
				pw.print(arr[i]+" ");
			pw.println(arr[arr.length-1]);
		}
		public void println(Integer[] arr) throws IOException{
			for(int i=0; i<arr.length-1; i++)
				pw.print(arr[i]+" ");
			pw.println(arr[arr.length-1]);
		}
		public void println(long[] arr) throws IOException{
			for(int i=0; i<arr.length-1; i++)
				pw.print(arr[i]+" ");
			pw.println(arr[arr.length-1]);
		}
		public void println(Long[] arr) throws IOException{
			for(int i=0; i<arr.length-1; i++)
				pw.print(arr[i]+" ");
			pw.println(arr[arr.length-1]);
		}
		public void println(char[] arr) throws IOException{
			for(int i=0; i<arr.length-1; i++)
				pw.print(arr[i]+" ");
			pw.println(arr[arr.length-1]);
		}
		public void println(Character[] arr) throws IOException{
			for(int i=0; i<arr.length-1; i++)
				pw.print(arr[i]+" ");
			pw.println(arr[arr.length-1]);
		}
		public void println(ArrayList<Integer> arr) throws IOException{
			for(int i=0; i<arr.size()-1; i++)
				pw.print(arr.get(i)+" ");
			pw.println(arr.get(arr.size()-1));
		}
		public void println(TreeSet<Integer> arr) throws IOException{
			for(int x: arr) {
				pw.print(x+" ");
			}
		}
		public void close() throws IOException{
			pw.close();
		}
		public void flush() throws IOException{
			pw.flush();
		}
	}
	static class Pair implements Comparable<Pair>{
		int x;
		int y;
		public Pair(int a, int b) {
			this.x=a;
			this.y=b;
		}
		public int compareTo(Pair other) {
			return -1*(this.y-other.y);
		}
	}
	static class Triple implements Comparable<Triple>{
		int x;
		int y;
		boolean d;
		public Triple(int a, int b, boolean t) {
			this.x=a;
			this.y=b;
			this.d=t;
		}
		public int compareTo(Triple other) {
			if(this.d && !other.d) {
				return 1;
			}else if(!this.d && other.d) {
				return -1;
			}else {
				return this.y-other.y;
			}
		}
	}
}


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

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

class TaskA {
    public void solve(int testNumber, Scanner in, PrintWriter out) {
        long n = in.nextLong(), p3 = 3;
        for(; n%p3 == 0; p3 *= 3);
        out.println(n/p3 + 1);
    }
}


/*package whatever //do not write package name here */

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

public class solution {
	public static void main (String[] args) {
	    Scanner sc = new Scanner(System.in);
	    int n = sc.nextInt();
	    int m = sc.nextInt();
	    int [] a = new int[m];
	   int diff = 1000;
	    for(int i=0;i<m;i++)
	    {
	       a[i] = sc.nextInt();
	    }
	       Arrays.sort(a);

	       for(int i=0;i<=(m-n);i++)
	       {
	          if(a[i+n-1]-a[i]<=diff)
	          {
	            diff = a[i+n-1]-a[i];
	          }
	       }

	    System.out.print(diff);
	   }
	}


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

/**
 * 4 4
 * 1 5 3 4
 * 1 2
 * 1 3
 * 2 3
 * 3 3
 *
 *
 * @author pttrung
 */
public class A {

    public static long Mod = (long) (1e9) + 7;
    static int time = 1;
    static long[] dp;

    public static void main(String[] args) throws FileNotFoundException {
        PrintWriter out = new PrintWriter(System.out);
        Scanner in = new Scanner();
        long n = in.nextLong();
        long x = in.nextLong() - 1;
        long y = in.nextLong() - 1;
        long c = in.nextLong();
        long start = 0;
        long end = 2*n;
        long result = end;
        while (start <= end) {
            long mid = (start + end) / 2;
            long total = cal(x,y,mid,n);
            if (total < c) {
                start = mid + 1;
            } else if (total >= c) {
                result = Math.min(result, mid);
                end = mid - 1;
            }
        }
        out.println(result);
        out.close();
    }

  static long cal(long x, long y , long l, long n){
      long minX = min(x - l);
      long maxX = max(x + l, n);
      long minY = min(y - l);
      long maxY = max(y + l, n);
      long total = 0;
      if(maxX != x + l){
          long c = x + l - maxX;
          long left = l - (maxY - y);
          if(left + x > maxX){
              long a = x + left - maxX;
              total -= (a + c)*(maxY - y + 1)/2;
          }else{
              total -= c*(c + 1)/2;
          }
      }
      if(minX != x - l){
          long c = minX - (x - l);
          long left = l - (maxY - y);
          if(x - left < minX){
              long a = minX - (x - left);
              total -= (a + c)*(maxY - y + 1)/2;
          }else{
              total -= c*(c + 1)/2;
          }
      }
      if(maxY < y + l){
          long c = y + l - maxY;
          long last = 2*c - 1;
          total -= (last + 1)*c/2;
      }
      long last = l*2 + 1;
      total += (last + 1)*(l + 1)/2;
      if(maxX != x + l){
          long c = x + l - maxX;
          long left = l - (y - minY);
          if(left + x > maxX){
              long a = x + left - maxX;
              total -= (a + c)*(y - minY + 1)/2;
          }else{
              total -= c*(c + 1)/2;
          }
      }
      if(minX != x - l){
          long c = minX - (x - l);
          long left = l - (y - minY);
          if(x - left < minX){
              long a = minX - (x - left);
              total -= (a + c)*(y - minY + 1)/2;
          }else{
              total -= c*(c + 1)/2;
          }
      }
      if(minY > y - l){
          long c = minY - (y - l);
          last = 2*c - 1;
          total -= (last + 1)*c/2;
      }
      last = l*2 + 1;
      total += (last + 1)*(l + 1)/2;
      total -= (maxX - minX + 1);
      return total;
  }

  static long max(long v, long n){
      if(v < n){
          return v;
      }
      return n - 1;
  }
  static long min(long v){
      if(v > 0){
          return v;
      }
      return 0;
  }

    static long squareDist(int x, int y) {
        long X = x;
        long Y = y;
        return X * X + Y * Y;
    }

    static int find(int index, int[] u) {
        if (index != u[index]) {
            return u[index] = find(u[index], u);
        }
        return index;
    }

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

    public static int[][] powSquareMatrix(int[][] A, long p) {
        int[][] unit = new int[A.length][A.length];
        for (int i = 0; i < unit.length; i++) {
            unit[i][i] = 1;
        }
        if (p == 0) {
            return unit;
        }
        int[][] val = powSquareMatrix(A, p / 2);
        if (p % 2 == 0) {
            return mulMatrix(val, val);
        } else {
            return mulMatrix(A, mulMatrix(val, val));
        }

    }

    public static int[][] mulMatrix(int[][] A, int[][] B) {
        int[][] result = new int[A.length][B[0].length];
        for (int i = 0; i < result.length; i++) {
            for (int j = 0; j < result[0].length; j++) {
                long temp = 0;
                for (int k = 0; k < A[0].length; k++) {

                    temp += ((long) A[i][k] * B[k][j] % Mod);
                    temp %= Mod;
                }
                temp %= Mod;
                result[i][j] = (int) temp;
            }
        }

        return result;
    }

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

    }

    static class FT {

        int[] data;

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

        void update(int index, int val) {
            // System.out.println("UPDATE INDEX " + index);
            while (index < data.length) {
                data[index] += val;
                index += index & (-index);

                //    System.out.println("NEXT " +index);
            }
        }

        int get(int index) {
            //  System.out.println("GET INDEX " + index);
            int result = 0;
            while (index > 0) {
                result += data[index];
                index -= index & (-index);
                // System.out.println("BACK " + index);
            }
            return result;
        }
    }

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

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

            return val * val % Mod;
        } else {
            return (val * val % Mod) * a % Mod;
        }
    }

//    static Point intersect(Point a, Point b, Point c) {
//        double D = cross(a, b);
//        if (D != 0) {
//            return new Point(cross(c, b) / D, cross(a, c) / D);
//        }
//        return null;
//    }
//
//    static Point convert(Point a, double angle) {
//        double x = a.x * cos(angle) - a.y * sin(angle);
//        double y = a.x * sin(angle) + a.y * cos(angle);
//        return new Point(x, y);
//    }
    static Point minus(Point a, Point b) {
        return new Point(a.x - b.x, a.y - b.y);
    }
//
//    static Point add(Point a, Point b) {
//        return new Point(a.x + b.x, a.y + b.y);
//    }
//

    /**
     * Cross product ab*ac
     *
     * @param a
     * @param b
     * @param c
     * @return
     */
    static double cross(Point a, Point b, Point c) {
        Point ab = new Point(b.x - a.x, b.y - a.y);
        Point ac = new Point(c.x - a.x, c.y - a.y);
        return cross(ab, ac);
    }

    static double cross(Point a, Point b) {
        return a.x * b.y - a.y * b.x;
    }

    /**
     * Dot product ab*ac;
     *
     * @param a
     * @param b
     * @param c
     * @return
     */
    static long dot(Point a, Point b, Point c) {
        Point ab = new Point(b.x - a.x, b.y - a.y);
        Point ac = new Point(c.x - a.x, c.y - a.y);
        return dot(ab, ac);
    }

    static long dot(Point a, Point b) {
        long total = a.x * b.x;
        total += a.y * b.y;
        return total;
    }

    static double dist(Point a, Point b) {
        long total = (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y);
        return Math.sqrt(total);
    }

    static long norm(Point a) {
        long result = a.x * a.x;
        result += a.y * a.y;
        return result;
    }

    static double dist(Point a, Point b, Point x, boolean isSegment) {
        double dist = cross(a, b, x) / dist(a, b);
        // System.out.println("DIST " + dist);

        if (isSegment) {
            Point ab = new Point(b.x - a.x, b.y - a.y);

            long dot1 = dot(a, b, x);
            long norm = norm(ab);
            double u = (double) dot1 / norm;
            if (u < 0) {
                return dist(a, x);
            }

            if (u > 1) {
                return dist(b, x);
            }
        }
        return Math.abs(dist);

    }

    static long squareDist(Point a, Point b) {
        long x = a.x - b.x;
        long y = a.y - b.y;
        return x * x + y * y;
    }

    static class Point {

        int x, y;

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

        @Override
        public String toString() {
            return "Point{" + "x=" + x + ", y=" + y + '}';
        }
    }

    static class Scanner {

        BufferedReader br;
        StringTokenizer st;

        public Scanner() throws FileNotFoundException {
            //System.setOut(new PrintStream(new BufferedOutputStream(System.out), true));
            br = new BufferedReader(new InputStreamReader(System.in));
            //br = new BufferedReader(new FileReader(new File("A-large (2).in")));
        }

        public String next() {

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

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

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

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

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

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


import java.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.InputStreamReader;
import java.io.InputStream;

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

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

            int[] knights = new int[n + 1];
            int[] colors = new int[m + 1];

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

            int totalKnightsNeeded = 0;
            for (int i = 1; i <= m; i++) {
                colors[i] = in.nextInt();
                totalKnightsNeeded += colors[i];
            }

            for (int i = 0; i <= Math.min(n - 1, (n - totalKnightsNeeded)); i++) {
                int[] c1 = colors.clone();
                boolean canDo = true;
                for (int j = 0; j < totalKnightsNeeded; j++) {
                    c1[knights[i + j]]--;
                    if (c1[knights[i + j]] < 0) {
                        canDo = false;
                        break;
                    }
                }
                if (canDo) {
                    out.println("YES");
                    return;
                }
            }

            out.println("NO");
        }

    }

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

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

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

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

    }
}


import java.util.*;
public class ProbC {

   public static void main(String[] args) {
      int adj[][] = new int[7][7];
      Scanner sc = new Scanner (System.in);
      int n=sc.nextInt(), m=sc.nextInt();

      if (n == 7) {
         for (int i = 0; i < m; i++) {
            int u, v;
            u = sc.nextInt();
            v= sc.nextInt();
            u--;
            v--;
            adj[u][v] = adj[v][u] = 1;
         }
         int d = m;
         for (int u = 0; u < n; u++) {
            for (int v = u + 1; v < n; v++) {
               int c = 0;
               for (int w = 0; w < n; w++) {
                  if (adj[u][w] ==1 && adj[v][w]==1) {
                     c++;
                  }
               }
               d = Math.min(d, c);
            }
         }
         m -= d;
      }
      System.out.println(m);

   }
}


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

/**
 * Created by Timur on 15.12.2016.
 */
public class _630K {
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        PrintWriter out = new PrintWriter(System.out);
        long n = in.nextLong();
        long first = n / 2 + n / 3 + n / 5 + n / 7;
        long second = n / (2 * 3) + n / (2 * 5) + n / (2 * 7) + n / (3 * 5) +n / (3 * 7) +n / (5 * 7);
        long third = n / (2 * 3 * 5) + n / (2 * 3 * 7) + n / (2 * 5 * 7) + n / (3 * 5 * 7);
        long forth = n / (2 * 3 * 5 * 7);

        out.print(n - first + second - third + forth);
        out.close();
    }
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;

public class B {

	final int MOD = 1000000007;
	final double eps = 1e-12;

	public B () throws IOException {
		int B = sc.nextInt();
		int D = sc.nextInt();

		start();

		int T2 = t2(B,D);
		if (T2 > 0) {
			print("2-type");
			exit(T2);
		}

		if (t3(B,D))
			exit("3-type");

		if (t11(B,D))
			exit("11-type");

		for (int d1 = 2; d1 <= 50; ++d1)
			for (int d2 = 2; d2 <= 50; ++d2)
					if (d1*d2 == D && gcd(d1,d2) == 1) {
						if (t2(B,d1) > 0 && t3(B,d2)) exit("6-type");
						if (t2(B,d1) > 0 && t11(B,d2)) exit("6-type");
						if (t3(B,d1) && t11(B,d2)) exit("6-type");
					}

		for (int d1 = 2; d1 <= 25; ++d1)
			for (int d2 = 2; d2 <= 25; ++d2)
				for (int d3 = 2; d3 <= 25; ++d3)
					if (d1*d2*d3 == D && gcd(d1,d2) == 1 && gcd(d1*d2,d3) == 1 && t2(B,d1) > 0 && t3(B,d2) && t11(B,d3))
						exit("6-type");

		exit("7-type");
	}

	int t2(int B, int D) {
		long P = B;
		for (int i = 0; i < 6; ++i) {
			if (P % D == 0)
				return i+1;
			P = P * B;
		}
		return -1;
	}

	boolean t3(int B, int D) {
		return B%D == 1;
	}

	boolean t11(int B, int D) {
		return (B+1)%D == 0;
	}

	int gcd(int x, int y) {
		return BigInteger.valueOf(x).gcd(BigInteger.valueOf(y)).intValue();
	}
	////////////////////////////////////////////////////////////////////////////////////

	static MyScanner sc;

	static void print (Object... a) {
		StringBuffer b = new StringBuffer();
		for (Object o : a)
			b.append(" ").append(o);
		System.out.println(b.toString().trim());
	}

	static void exit (Object... a) {
		print(a);
		System.out.flush();
		exit();
	}

	static void exit () {
		System.err.println("------------------");
		System.err.println("Time: " + (millis() - t) / 1000.0);
		System.exit(0);
	}

	static class MyScanner {
		String next() throws IOException {
			newLine();
			return line[index++];
		}

		char [] nextChars() throws IOException {
			return next().toCharArray();
		}

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

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

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

		String nextLine() throws IOException {
			line = null;
			return r.readLine();
		}

		String [] nextStrings() throws IOException {
			line = null;
			return r.readLine().split(" ");
		}

		int [] nextInts() throws IOException {
			String [] L = nextStrings();
			int [] res = new int [L.length];
			for (int i = 0; i < L.length; ++i)
				res[i] = Integer.parseInt(L[i]);
			return res;
		}

		long [] nextLongs() throws IOException {
			String [] L = nextStrings();
			long [] res = new long [L.length];
			for (int i = 0; i < L.length; ++i)
				res[i] = Long.parseLong(L[i]);
			return res;
		}

		boolean eol() {
			return index == line.length;
		}

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

		private final BufferedReader r;

		MyScanner () throws IOException {
			this(new BufferedReader(new InputStreamReader(System.in)));
		}

		MyScanner(BufferedReader r) throws IOException {
			this.r = r;
		}

		private String [] line;
		private int index;

		private void newLine() throws IOException {
			if (line == null || eol()) {
				line = r.readLine().split(" ");
				index = 0;
			}
		}
	}

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

	public static void main(String[] args) throws IOException {
		run();
		exit();
	}

	static void start() {
		t = millis();
	}

	static void run () throws IOException {
		sc = new MyScanner ();
		new B();
	}

	static long t;

	static long millis() {
		return System.currentTimeMillis();
	}
}


import java.util.*;
public class Main{
    public static void main(String[] args){
        Scanner sc=new Scanner (System.in);
        int t=sc.nextInt();
        while(t--!=0){
            int n=sc.nextInt();
            if(100%n==0){
                int ans=100/n;
                System.out.println(ans);
            }
            else{
              int x=n;
              int y=100-n;
              int gc=gcd(x,y);
              int ans=(x/gc)+(y/gc);
              System.out.println(ans);
            }
        }
    }
    public static int gcd(int a,int b){
        if (b == 0)
            return a;
        return gcd(b, a % b);
    }
}


import java.util.HashMap;
import java.util.Scanner;

public class ProblemF {

	static String[] word;

	static HashMap<String, Pair> hash;

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		word = new String[n];
		for (int i = 0; i < n; i++) {
			word[i] = sc.next();
		}
		boolean win = false;
		Pair winpts = null;
		Pair losepts = null;
		hash = new HashMap<String, Pair>();
		for (char c = 'a'; c <= 'z'; c++) {
			if (!ok("" + c)) {
				continue;
			}
			Pair res = play("" + c);
			long nmy = getScore("" + c) + res.other;
			if (!res.win) {
				win = true;
				if (winpts == null) {
					winpts = new Pair(0, 0, true);
					winpts.my = nmy;
					winpts.other = res.my;
				} else {
					if (winpts.my < nmy || (winpts.my == nmy && winpts.other > res.my)) {
						winpts.my = nmy;
						winpts.other = res.my;
					}
				}
			} else {
				if (losepts ==  null) {
					losepts = new Pair(0, 0, false);
					losepts.my = nmy;
					losepts.other = res.my;
				} else {
					if (losepts.my < nmy || (losepts.my == nmy && losepts.other > res.my)) {
						losepts.my = nmy;
						losepts.other = res.my;
					}
				}
			}
		}
		if (win) {
			System.out.println("First");
			System.out.println(winpts.my + " " + winpts.other);
		} else {
			System.out.println("Second");
			System.out.println(losepts.my + " " + losepts.other);
		}
	}

	static int count(String w) {
		int ret = 0;
		for (int i = 0; i < word.length; i++) {
			if (word[i].indexOf(w) >= 0) {
				ret++;
			}
		}
		return ret;
	}
	static boolean ok(String w) {
		return count(w) > 0;
	}

	private static Pair play(String current) {
		if (hash.containsKey(current)) {
			return hash.get(current);
		}
		Pair winpts = new Pair(0, 0, true);
		Pair losepts = new Pair(0, 0, false);
		boolean canwin = false;
		for (char c = 'a'; c <= 'z'; c++) {
			String nword1 = c + current;
			String nword2 = current + c;
			if (ok(nword1)) {
				Pair res = play(nword1);
				long nmy = getScore(nword1) + res.other;
				if (!res.win) {
					canwin = true;
					if (winpts == null) {
						winpts = new Pair(0, 0, true);
						winpts.my = nmy;
						winpts.other = res.my;
					} else {
						if (winpts.my < nmy || (winpts.my == nmy && winpts.other > res.my)) {
							winpts.my = nmy;
							winpts.other = res.my;
						}
					}
				} else {
					if (losepts ==  null) {
						losepts = new Pair(0, 0, false);
						losepts.my = nmy;
						losepts.other = res.my;
					} else {
						if (losepts.my < nmy || (losepts.my == nmy && losepts.other > res.my)) {
							losepts.my = nmy;
							losepts.other = res.my;
						}
					}
				}
			}
			if (ok(nword2)) {
				Pair res = play(nword2);
				long nmy = getScore(nword2) + res.other;
				if (!res.win) {
					canwin = true;
					if (winpts == null) {
						winpts = new Pair(0, 0, true);
						winpts.my = nmy;
						winpts.other = res.my;
					} else {
						if (winpts.my < nmy || (winpts.my == nmy && winpts.other > res.my)) {
							winpts.my = nmy;
							winpts.other = res.my;
						}
					}
				} else {
					if (losepts ==  null) {
						losepts = new Pair(0, 0, false);
						losepts.my = nmy;
						losepts.other = res.my;
					} else {
						if (losepts.my < nmy || (losepts.my == nmy && losepts.other > res.my)) {
							losepts.my = nmy;
							losepts.other = res.my;
						}
					}
				}
			}
		}
		if (canwin) {
			hash.put(current, winpts);
			return winpts;
		} else {
			hash.put(current, losepts);
			return losepts;
		}
	}

	private static int getScore(String word) {
		int sum = 0;
		int max = 0;
		for (char c : word.toCharArray()) {
			sum += (int)(c - 'a' + 1);
			max = Math.max(max, (int)(c - 'a' + 1));
		}
		return sum * max + count(word);
	}
}

class Pair {
	long my, other;
	boolean win;

	public Pair(long my, long other, boolean win) {
		super();
		this.my = my;
		this.other = other;
		this.win = win;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + (int) (my ^ (my >>> 32));
		result = prime * result + (int) (other ^ (other >>> 32));
		result = prime * result + (win ? 1231 : 1237);
		return result;
	}

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

}


import java.util.*;

public class E {

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

		int a = sc.nextInt(), b = sc.nextInt(), p = sc.nextInt();
		long x = sc.nextLong();

		long arr[] = new long[p];
		arr[p-1] = 1;
		for(int i=p-2;i>=0;i--){
			arr[i] = arr[i+1] * a % p;
		}

		long ans = 0;
		long T = (long)p*(p-1);

		for(int i = 1;i<=p-1;i++){
			long j = (i- b * arr[i]) % p;
			while(j < 0){
				j+=p;
			}

			long n = j * (p-1) + i;

			ans += x/T;
			if(x % T >= n)
				ans++;
		}

		System.out.println(ans);

	}

}


import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        long a = scanner.nextLong();
        long b = scanner.nextLong();
        long c = scanner.nextLong();
        scanner.close();

        long result = c * 2;
        long t = Math.min(a, b);
        result += t * 2;
        if (b > t) {
            result++;
        }
        if (a > t) {
            result++;
        }
        System.out.println(result);
    }
}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.PrintStream;
import java.util.Arrays;
import java.io.IOException;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) throws Exception {
        Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 29);
        thread.start();
        thread.join();
    }

    static class TaskAdapter implements Runnable {
        @Override
        public void run() {
            InputStream inputStream = System.in;
            OutputStream outputStream = System.out;
            FastInput in = new FastInput(inputStream);
            PrintWriter out = new PrintWriter(outputStream);
            DGraphAndQueries solver = new DGraphAndQueries();
            solver.solve(1, in, out);
            out.close();
        }
    }

    static class DGraphAndQueries {
        Debug debug = new Debug(true);

        public void solve(int testNumber, FastInput in, PrintWriter out) {
            int n = in.readInt();
            int m = in.readInt();
            int q = in.readInt();
            int[] p = new int[n];
            in.populate(p);

            Edge[] edges = new Edge[m];
            for (int i = 0; i < m; i++) {
                edges[i] = new Edge();
                edges[i].a = in.readInt() - 1;
                edges[i].b = in.readInt() - 1;
            }

            int[][] qs = new int[4][q];
            for (int i = 0; i < q; i++) {
                for (int j = 0; j < 2; j++) {
                    qs[j][i] = in.readInt();
                }
                if (qs[0][i] == 2) {
                    edges[qs[1][i] - 1].delete = true;
                }
            }

            DSUExt dsu = new DSUExt(n);
            dsu.reset();
            for (Edge e : edges) {
                if (e.delete) {
                    continue;
                }
                dsu.merge(e.a, e.b);
            }

            for (int i = q - 1; i >= 0; i--) {
                if (qs[0][i] == 2) {
                    Edge e = edges[qs[1][i] - 1];
                    dsu.merge(e.a, e.b);
                } else {
                    int v = qs[1][i] - 1;
                    int pa = dsu.find(v);
                    qs[2][i] = dsu.begin[pa];
                    qs[3][i] = dsu.end[pa];
                }
            }

            int[] id = new int[n];
            int[] inv = new int[n];
            int idAlloc = 0;
            for (int i = 0; i < n; i++) {
                if (dsu.find(i) != i) {
                    continue;
                }
                for (int trace = dsu.begin[i]; trace != -1; trace = dsu.next[trace]) {
                    id[trace] = idAlloc++;
                    inv[id[trace]] = trace;
                }
            }

            Segment seg = new Segment(0, n - 1, i -> p[inv[i]]);
            debug.debug("seg", seg);
            for (int i = 0; i < q; i++) {
                if (qs[0][i] != 1) {
                    continue;
                }
                int l = id[qs[2][i]];
                int r = id[qs[3][i]];
                if (l > r) {
                    int tmp = l;
                    l = r;
                    r = tmp;
                }
                int ans = seg.query(l, r, 0, n - 1);
                seg.pop(l, r, 0, n - 1, ans);
                out.println(ans);

                debug.debug("debug", seg);
            }
        }

    }

    static class Segment implements Cloneable {
        private Segment left;
        private Segment right;
        private int max;

        private void modify(int x) {
            max = x;
        }

        public void pushUp() {
            max = Math.max(left.max, right.max);
        }

        public void pushDown() {
        }

        public Segment(int l, int r, IntToIntegerFunction func) {
            if (l < r) {
                int m = DigitUtils.floorAverage(l, r);
                left = new Segment(l, m, func);
                right = new Segment(m + 1, r, func);
                pushUp();
            } else {
                max = func.apply(l);
            }
        }

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

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

        public boolean pop(int ll, int rr, int l, int r, int maxVal) {
            if (noIntersection(ll, rr, l, r)) {
                return false;
            }
            if (covered(ll, rr, l, r)) {
                if (max != maxVal) {
                    return false;
                }
                if (l == r) {
                    modify(0);
                    return true;
                }
            }
            pushDown();
            int m = DigitUtils.floorAverage(l, r);
            boolean ans = left.pop(ll, rr, l, m, maxVal);
            if (!ans) {
                ans = right.pop(ll, rr, m + 1, r, maxVal);
            }
            pushUp();
            return ans;
        }

        public int query(int ll, int rr, int l, int r) {
            if (noIntersection(ll, rr, l, r)) {
                return 0;
            }
            if (covered(ll, rr, l, r)) {
                return max;
            }
            pushDown();
            int m = DigitUtils.floorAverage(l, r);
            return Math.max(left.query(ll, rr, l, m),
                    right.query(ll, rr, m + 1, r));
        }

        private Segment deepClone() {
            Segment seg = clone();
            if (seg.left != null) {
                seg.left = seg.left.deepClone();
            }
            if (seg.right != null) {
                seg.right = seg.right.deepClone();
            }
            return seg;
        }

        protected Segment clone() {
            try {
                return (Segment) super.clone();
            } catch (CloneNotSupportedException e) {
                throw new RuntimeException(e);
            }
        }

        private void toString(StringBuilder builder) {
            if (left == null && right == null) {
                builder.append(max).append(",");
                return;
            }
            pushDown();
            left.toString(builder);
            right.toString(builder);
        }

        public String toString() {
            StringBuilder builder = new StringBuilder();
            deepClone().toString(builder);
            if (builder.length() > 0) {
                builder.setLength(builder.length() - 1);
            }
            return builder.toString();
        }

    }

    static class Debug {
        private boolean offline;
        private PrintStream out = System.err;
        static int[] empty = new int[0];

        public Debug(boolean enable) {
            offline = enable && System.getSecurityManager() == null;
        }

        public Debug debug(String name, Object x) {
            return debug(name, x, empty);
        }

        public Debug debug(String name, Object x, int... indexes) {
            if (offline) {
                if (x == null || !x.getClass().isArray()) {
                    out.append(name);
                    for (int i : indexes) {
                        out.printf("[%d]", i);
                    }
                    out.append("=").append("" + x);
                    out.println();
                } else {
                    indexes = Arrays.copyOf(indexes, indexes.length + 1);
                    if (x instanceof byte[]) {
                        byte[] arr = (byte[]) x;
                        for (int i = 0; i < arr.length; i++) {
                            indexes[indexes.length - 1] = i;
                            debug(name, arr[i], indexes);
                        }
                    } else if (x instanceof short[]) {
                        short[] arr = (short[]) x;
                        for (int i = 0; i < arr.length; i++) {
                            indexes[indexes.length - 1] = i;
                            debug(name, arr[i], indexes);
                        }
                    } else if (x instanceof boolean[]) {
                        boolean[] arr = (boolean[]) x;
                        for (int i = 0; i < arr.length; i++) {
                            indexes[indexes.length - 1] = i;
                            debug(name, arr[i], indexes);
                        }
                    } else if (x instanceof char[]) {
                        char[] arr = (char[]) x;
                        for (int i = 0; i < arr.length; i++) {
                            indexes[indexes.length - 1] = i;
                            debug(name, arr[i], indexes);
                        }
                    } else if (x instanceof int[]) {
                        int[] arr = (int[]) x;
                        for (int i = 0; i < arr.length; i++) {
                            indexes[indexes.length - 1] = i;
                            debug(name, arr[i], indexes);
                        }
                    } else if (x instanceof float[]) {
                        float[] arr = (float[]) x;
                        for (int i = 0; i < arr.length; i++) {
                            indexes[indexes.length - 1] = i;
                            debug(name, arr[i], indexes);
                        }
                    } else if (x instanceof double[]) {
                        double[] arr = (double[]) x;
                        for (int i = 0; i < arr.length; i++) {
                            indexes[indexes.length - 1] = i;
                            debug(name, arr[i], indexes);
                        }
                    } else if (x instanceof long[]) {
                        long[] arr = (long[]) x;
                        for (int i = 0; i < arr.length; i++) {
                            indexes[indexes.length - 1] = i;
                            debug(name, arr[i], indexes);
                        }
                    } else {
                        Object[] arr = (Object[]) x;
                        for (int i = 0; i < arr.length; i++) {
                            indexes[indexes.length - 1] = i;
                            debug(name, arr[i], indexes);
                        }
                    }
                }
            }
            return this;
        }

    }

    static class DSUExt extends DSU {
        int[] begin;
        int[] end;
        int[] next;

        public DSUExt(int n) {
            super(n);
            begin = new int[n];
            end = new int[n];
            next = new int[n];
        }

        public void reset() {
            super.reset();
            for (int i = 0; i < begin.length; i++) {
                begin[i] = end[i] = i;
                next[i] = -1;
            }
        }

        protected void preMerge(int a, int b) {
            next[end[a]] = begin[b];
            end[a] = end[b];
        }

    }

    static interface IntToIntegerFunction {
        int apply(int x);

    }

    static class DigitUtils {
        private DigitUtils() {
        }

        public static int floorAverage(int x, int y) {
            return (x & y) + ((x ^ y) >> 1);
        }

    }

    static class FastInput {
        private final InputStream is;
        private byte[] buf = new byte[1 << 13];
        private int bufLen;
        private int bufOffset;
        private int next;

        public FastInput(InputStream is) {
            this.is = is;
        }

        public void populate(int[] data) {
            for (int i = 0; i < data.length; i++) {
                data[i] = readInt();
            }
        }

        private int read() {
            while (bufLen == bufOffset) {
                bufOffset = 0;
                try {
                    bufLen = is.read(buf);
                } catch (IOException e) {
                    bufLen = -1;
                }
                if (bufLen == -1) {
                    return -1;
                }
            }
            return buf[bufOffset++];
        }

        public void skipBlank() {
            while (next >= 0 && next <= 32) {
                next = read();
            }
        }

        public int readInt() {
            int sign = 1;

            skipBlank();
            if (next == '+' || next == '-') {
                sign = next == '+' ? 1 : -1;
                next = read();
            }

            int val = 0;
            if (sign == 1) {
                while (next >= '0' && next <= '9') {
                    val = val * 10 + next - '0';
                    next = read();
                }
            } else {
                while (next >= '0' && next <= '9') {
                    val = val * 10 - next + '0';
                    next = read();
                }
            }

            return val;
        }

    }

    static class DSU {
        protected int[] p;
        protected int[] rank;

        public DSU(int n) {
            p = new int[n];
            rank = new int[n];
        }

        public void reset() {
            for (int i = 0; i < p.length; i++) {
                p[i] = i;
                rank[i] = 0;
            }
        }

        public final int find(int a) {
            if (p[a] == p[p[a]]) {
                return p[a];
            }
            preAccess(a);
            return p[a] = find(p[a]);
        }

        protected void preAccess(int a) {

        }

        protected void preMerge(int a, int b) {

        }

        public final void merge(int a, int b) {
            a = find(a);
            b = find(b);
            if (a == b) {
                return;
            }
            if (rank[a] == rank[b]) {
                rank[a]++;
            }

            if (rank[a] < rank[b]) {
                int tmp = a;
                a = b;
                b = tmp;
            }

            preMerge(a, b);
            p[b] = a;
        }

    }

    static class Edge {
        int a;
        int b;
        boolean delete;

    }
}


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

import static java.lang.Math.*;
import static java.util.Arrays.*;

public class Main {
    static long n;
    static long log;
    static long calc(long a) {
        long fa = a;
        long rt = 0;
        long lgt = getLength(a);
        for (long i = lgt + 1; i < log; i++) {
            rt += (1L << (i - lgt));
        }
        a <<= (log - lgt);
        int eql = 0;
        for (long i = log - 1; i >= log - lgt; i--) {
            if (getBit(a, i) != getBit(n, i)) {
                eql = getBit(a, i) > getBit(n, i) ? 1 : -1;
                break;
            }
        }
        if (eql == 1) return rt;
        if (eql == -1) return rt + (log == lgt ? 0 : (1L << (log - lgt)));
        long zrs = log - lgt;
        for (long i = log - lgt - 1; i >= 0; i--) {
            if (getBit(n, i) == 1) rt += ((1L << (zrs - 1L)));
            zrs--;
        }
        return rt + (fa == n ? 0L : 1L);
    }

    static long getBit(long a, long bit) {
        return (a >> bit) & 1L;
    }

    static long extraCalc(long a) {
            if ((a & 1) == 0) return calc(a) + ((a + 1L) <= n ? (calc(a + 1L) + 1L) : 0) + 1L;
             else return calc(a) + 1;
    }

    static long  getLength(long a) {
        for (long i = 63; i >= 0; i--) {
            if (getBit(a, i) == 1L) return i + 1L;
        }
        return 1L;
    }

    public static void main(String[] args) throws IOException {
        FastScanner in = new FastScanner(System.in);
        PrintWriter out = new PrintWriter(System.out);
        n = in.nextLong();
        log = getLength(n);
        long k = in.nextLong();
        long t = 0;
        while ((1L << t) <= n) ++t;
        long l = 0;
        while (t > 0) {
            while (t > 0 && ((l + (1L << t)) > n || extraCalc(l + (1L << t)) < k)) {
                t--;
            }
            if (t == 0) {
                if (extraCalc(l + 1) >= k && l + 1 <= n) l++;
            } else l = (l + (1L << t));
        }
        if (extraCalc(l + 1) >= k && l + 1 <= n) l++;
        if (extraCalc(l) < k || l > n) l--;
        out.println(l);
        out.close();
    }
}

class FastScanner {
    BufferedReader br;
    StringTokenizer st;

    FastScanner(File f) throws FileNotFoundException {
        br = new BufferedReader(new FileReader(f));
    }

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

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

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

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