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

public class Prg10 {

    PrintWriter pw = new PrintWriter(System.out);
    Random rnd = new Random();
    int a;
    long o =0, s, stt;

    void run() {
        s = nl();
        long[] m = new long[8];
        for(int q=0; q<8; q++) m[q] = nl();
        stt = System.currentTimeMillis();
        rec(m, 0);
        pw.print(o);
        pw.flush();
    }

    void rec(long[] m, long cur){
        if(System.currentTimeMillis()-stt>500) return;
        o = Math.max(o, cur);
        for(int q=0; q<8; q++){
            if((s-cur)%(q+1)>0) continue;
            long need = (s-cur)/(q+1);
            if(m[q]>=need){
                o = s;
                return;
            }
        }
        for(int q=7; q>=0; q--){
            long can = Math.min(m[q], (s-cur)/(q+1));
            for(long w=Math.max(1, can-10); w<=can; w++){
                m[q]-=w;
                rec(m, cur+(q+1)*w);
                m[q]+=w;
            }
        }
    }

    static class PyraSort {

        private static int heapSize;

        public static void sort(long[] a) {
            buildHeap(a);
            while (heapSize > 1) {
                swap(a, 0, heapSize - 1);
                heapSize--;
                heapify(a, 0);
            }
        }

        private static void buildHeap(long[] a) {
            heapSize = a.length;
            for (int i = a.length / 2; i >= 0; i--) {
                heapify(a, i);
            }
        }

        private static void heapify(long[] a, int i) {
            int l = 2 * i + 2;
            int r = 2 * i + 1;
            int largest = i;
            if (l < heapSize && a[i] < a[l]) {
                largest = l;
            }
            if (r < heapSize && a[largest] < a[r]) {
                largest = r;
            }
            if (i != largest) {
                swap(a, i, largest);
                heapify(a, largest);
            }
        }

        private static void swap(long[] a, int i, int j) {
            a[i] ^= a[j] ^= a[i];
            a[j] ^= a[i];
        }
    }

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

    InputStream is = System.in;
    private byte[] inbuf = new byte[1<<16];
    public int lenbuf = 0, ptrbuf = 0;

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

    private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
    private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }

    private double nd() { return Double.parseDouble(ns()); }
    private char nc() { return (char)skip(); }

    private String ns()
    {
        int b = skip();
        StringBuilder sb = new StringBuilder();
        while(!(isSpaceChar(b))){
            sb.appendCodePoint(b);
            b = readByte();
        }
        return sb.toString();
    }

    private String nline(){
        int b = readByte();
        StringBuilder sb = new StringBuilder();
        while (b!=10) {
            sb.appendCodePoint(b);
            b = readByte();
        }
        return sb.toString();
    }

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

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

    private int[] na(int n)
    {
        int[] a = new int[n];
        for(int i = 0;i < n;i++)a[i] = ni();
        return a;
    }

    private int ni()
    {
        int num = 0, b;
        boolean minus = false;
        while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
        if(b == '-'){
            minus = true;
            b = readByte();
        }
        while(true){
            if(b >= '0' && b <= '9'){
                num = num * 10 + (b - '0');
            }else{
                return minus ? -num : num;
            }
            b = readByte();
        }
    }

    private long nl()
    {
        long num = 0;
        int b;
        boolean minus = false;
        while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
        if(b == '-'){
            minus = true;
            b = readByte();
        }
        while(true){
            if(b >= '0' && b <= '9'){
                num = num * 10 + (b - '0');
            }else{
                return minus ? -num : num;
            }
            b = readByte();
        }
    }
}


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

import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.util.Arrays.fill;

public class Main {
    FastScanner in;
    PrintWriter out;

    private void solve() throws IOException {
        long W = in.nextLong();
        long[] cnt = new long[9];
        for (int i = 1; i <= 8; i++)
            cnt[i] = in.nextLong();

        int lcm = 840;
        long[][] dp = new long[9][lcm];
        for (int i = 0; i < 9; i++)
            fill(dp[i], -1);
        dp[0][0] = 0;
        for (int i = 1; i <= 8; i++) {
            for (int j = 0; j < lcm; j++) {
                if (dp[i - 1][j] != -1) {
                    for (int k = 0; k < min(lcm / i, cnt[i] + 1); k++) {
                        if (dp[i - 1][j] * lcm + j + k * i <= W) {
                            dp[i][(j + k * i) % lcm] = max(dp[i][(j + k * i) % lcm], dp[i - 1][j] + (j + k * i) / lcm + min((W - (dp[i - 1][j] * lcm + j + k * i)) / lcm, (cnt[i] - k) / (lcm / i)));
                        }
                    }
                }
            }
        }

        long ans = 0;
        for (int i = 0; i < lcm; i++) {
            if (dp[8][i] != -1) {
                ans = max(ans, dp[8][i] * lcm + i);
            }
        }
        out.println(ans);
    }

    class FastScanner {
        StringTokenizer st;
        BufferedReader br;

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

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

        boolean hasNext() throws IOException {
            return br.ready() || (st != null && st.hasMoreTokens());
        }

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

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

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

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

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

    private void run() throws IOException {
        in = new FastScanner(System.in); // new FastScanner(new FileInputStream(".in"));
        out = new PrintWriter(System.out); // new PrintWriter(new FileOutputStream(".out"));

        solve();

        out.flush();
        out.close();
    }

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


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

public class Prg10 {

    PrintWriter pw = new PrintWriter(System.out);
    Random rnd = new Random();
    int a;
    long o =0, s, stt;

    void run() {
        //a = ni();
        s = nl();
        long sum=0;
        long[] m = new long[8];
        for(int q=0; q<8; q++) {
            m[q] = nl();
            sum+=m[q]*(q+1);
        }
        if(sum<=s){
            System.out.println(sum);
            return;
        }
        stt = System.currentTimeMillis();
        rec(m, 0);
        pw.print(o);
        pw.flush();
    }

    void rec(long[] m, long cur){
        if(o==s) return;
        if(System.currentTimeMillis()-stt>1400) return;
        o = Math.max(o, cur);
        for(int q=0; q<8; q++){
            if((s-cur)%(q+1)>0) continue;
            long need = (s-cur)/(q+1);
            if(m[q]>=need){
                o = s;
                return;
            }
        }
        for(long q=7; q>=0; q--){
            if(m[(int)q]==0) continue;
            if(o==s) return;
            long can = Math.min(m[(int)q], (s-cur)/(q+1));
            if(can==0) continue;
            for(long w=Math.max(1, can-10), i=0; i<10 && w<=can; w++, i++){
                m[(int)q]-=w;
                rec(m, cur+(q+1)*w);
                m[(int)q]+=w;
            }
        }
    }

    static class PyraSort {

        private static int heapSize;

        public static void sort(long[] a) {
            buildHeap(a);
            while (heapSize > 1) {
                swap(a, 0, heapSize - 1);
                heapSize--;
                heapify(a, 0);
            }
        }

        private static void buildHeap(long[] a) {
            heapSize = a.length;
            for (int i = a.length / 2; i >= 0; i--) {
                heapify(a, i);
            }
        }

        private static void heapify(long[] a, int i) {
            int l = 2 * i + 2;
            int r = 2 * i + 1;
            int largest = i;
            if (l < heapSize && a[i] < a[l]) {
                largest = l;
            }
            if (r < heapSize && a[largest] < a[r]) {
                largest = r;
            }
            if (i != largest) {
                swap(a, i, largest);
                heapify(a, largest);
            }
        }

        private static void swap(long[] a, int i, int j) {
            a[i] ^= a[j] ^= a[i];
            a[j] ^= a[i];
        }
    }

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

    InputStream is = System.in;
    private byte[] inbuf = new byte[1<<16];
    public int lenbuf = 0, ptrbuf = 0;

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

    private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
    private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }

    private double nd() { return Double.parseDouble(ns()); }
    private char nc() { return (char)skip(); }

    private String ns()
    {
        int b = skip();
        StringBuilder sb = new StringBuilder();
        while(!(isSpaceChar(b))){
            sb.appendCodePoint(b);
            b = readByte();
        }
        return sb.toString();
    }

    private String nline(){
        int b = readByte();
        StringBuilder sb = new StringBuilder();
        while (b!=10) {
            sb.appendCodePoint(b);
            b = readByte();
        }
        return sb.toString();
    }

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

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

    private int[] na(int n)
    {
        int[] a = new int[n];
        for(int i = 0;i < n;i++)a[i] = ni();
        return a;
    }

    private int ni()
    {
        int num = 0, b;
        boolean minus = false;
        while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
        if(b == '-'){
            minus = true;
            b = readByte();
        }
        while(true){
            if(b >= '0' && b <= '9'){
                num = num * 10 + (b - '0');
            }else{
                return minus ? -num : num;
            }
            b = readByte();
        }
    }

    private long nl()
    {
        long num = 0;
        int b;
        boolean minus = false;
        while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
        if(b == '-'){
            minus = true;
            b = readByte();
        }
        while(true){
            if(b >= '0' && b <= '9'){
                num = num * 10 + (b - '0');
            }else{
                return minus ? -num : num;
            }
            b = readByte();
        }
    }
}


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

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

    static class CF747F {
        String s = "0123456789abcdef";
        int[] av = new int[16];
        int[][] dp = new int[25][16];
        int[][] C = new int[25][25];

        public CF747F() {
            for (int i = 0; i < 25; i++)
                C[i][0] = 1;
            for (int i = 1; i < 25; i++) {
                for (int j = 1; j <= i; j++) {
                    C[i][j] = C[i - 1][j - 1] + C[i - 1][j];
                }
            }
        }

        int cal(int len) {
            if (len == 0) return 1;
            for (int i = 0; i < 16; i++)
                dp[0][i] = 1;
            for (int i = 1; i <= len; i++) {
                dp[i][0] = i <= av[0] ? 1 : 0;
                for (int j = 1; j < 16; j++) {
                    dp[i][j] = dp[i][j - 1];
                    for (int kk = 1; kk <= av[j] && kk <= i; kk++) {
                        dp[i][j] += dp[i - kk][j - 1] * C[i][kk];
                    }
                }
            }
            return dp[len][15];
        }

        public void solve(int testNumber, Scanner in, PrintWriter out) {
            int k = in.nextInt(), t = in.nextInt();
            Arrays.fill(av, t);
            int len, sum = 0;
            for (len = 1; ; len++) {
                boolean find = false;
                for (int fir = 1; fir < 16; fir++) {
                    av[fir]--;
                    int m = cal(len - 1);
                    if (sum + m >= k) {
                        find = true;
                        out.print(s.charAt(fir));
                        break;
                    }
                    sum += m;
                    av[fir]++;
                }
                if (find == true) break;
            }
            --len;
            while (--len >= 0) {
                int i;
                for (i = 0; i < 16; i++) {
                    if (av[i] > 0) {
                        av[i]--;
                        int m = cal(len);
                        if (sum + m >= k) {
                            out.print(s.charAt(i));
                            break;
                        }
                        av[i]++;
                        sum += m;
                    }
                }
            }
            out.println();
        }

    }
}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;

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

    static class TaskF {
        static boolean debug = false;
        int numberNumber;
        int t;
        long[][] bin = IntegerUtils.generateBinomialCoefficients(100);

        static {
            if (debug) {
                try {
                    FileOutputStream f = new FileOutputStream("file.txt");
                    System.setErr(new PrintStream(f));
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }

        public void solve(int testNumber, InputReader in, OutputWriter out) {
            numberNumber = in.readInt();
            t = in.readInt();

//        t = 1;

            //        HashMap<Integer, String> answers = new HashMap<>();
//
//        for (int i = 1, cnt = 0; cnt < 1e5; i++) {
//            int[] cntTake = new int[16];
//            for (char c : String.format("%x", i).toCharArray()) {
//                ++cntTake[Integer.parseInt("" + c, 16)];
//            }
//            boolean ok = true;
//            for (int c : cntTake) {
//                ok &= c <= t;
//            }
//            if (ok) {
//                ++cnt;
//                String answer = String.format("%x", i);
//                answers.put(cnt, answer);
//                System.err.println(cnt + " = " + answer);
//                System.err.flush();
//            }
//        }

//
//        for (int _numberNumber = 1; ; _numberNumber++) {
//            numberNumber = _numberNumber;
            int wordLength = 1;
            for (; ; wordLength++) {
                long[][] dp = new long[16][wordLength + 1];

                for (int length = 0; length <= wordLength; length++) {
                    for (int ch = 0; ch < 16; ch++) {
                        if (length == 0) {
                            dp[ch][length] = 1;
                        } else if (ch == 0) {
                            if (length <= t) {
                                dp[ch][length] = bin[wordLength - 1][length];
                            }
                        } else {
                            dp[ch][length] += dp[ch - 1][length];
                            for (int c = 1; c <= Math.min(length, t); c++) {
                                dp[ch][length] += bin[wordLength - length + c][c] * dp[ch - 1][length - c];
                            }
                        }
                    }
                }

                System.err.println("wordLength, dp: " + wordLength + " " + dp[15][wordLength]);
                System.err.flush();
                if (dp[15][wordLength] < numberNumber) {
                    numberNumber -= dp[15][wordLength];
                } else {
//                out.printLine("wordLength: " + wordLength);
                    break;
                }
            }

            StringBuilder ans = new StringBuilder();
            int[] maxCnt = new int[16];
            Arrays.fill(maxCnt, t);
            for (int pos = 0; pos < wordLength; pos++) {
                boolean addCh = false;
                for (int ch = 0; ch < 16; ch++) {
                    if (pos == 0 && ch == 0) {
                        continue;
                    }
                    if (maxCnt[ch] == 0) {
                        continue;
                    }
                    --maxCnt[ch];
                    long dp = getDp(wordLength - pos - 1, maxCnt);
                    if (numberNumber <= dp) {
                        ans.append(String.format("%x", ch));
                        addCh = true;
                        break;
                    } else {
                        ++maxCnt[ch];
                        numberNumber -= dp;
                    }
                }
                if (!addCh) {
                    throw new RuntimeException("no addCh");
//                    out.printLine("no add ch at pos=" + pos, "   : ", _numberNumber, answers.get(_numberNumber), ans);
//                    return;
                }
            }
//            if (!answers.get(_numberNumber).equals(ans.toString())) {
//                out.printLine("FUCK:", _numberNumber, answers.get(_numberNumber), ans);
//                return;
//            }
            out.printLine(ans);
//        }
        }

        private long getDp(int wordLength, int[] maxCnt) {
            long[][] dp = new long[16][wordLength + 1];
            for (int length = 0; length <= wordLength; length++) {
                for (int ch = 0; ch < 16; ch++) {
                    if (length == 0) {
                        dp[ch][length] = 1;
                    } else {
                        if (ch != 0) {
                            dp[ch][length] += dp[ch - 1][length];
                        }
                        for (int cnt = 1; cnt <= Math.min(length, maxCnt[ch]); cnt++) {
                            if (ch == 0) {
                                if (length == cnt) {
                                    dp[ch][length] += bin[wordLength][cnt];
                                }
                            } else {
                                dp[ch][length] += bin[wordLength - length + cnt][cnt] * dp[ch - 1][length - cnt];
                            }
                        }
                    }
                }
            }
            return dp[15][wordLength];
        }

    }

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

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

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

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

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

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

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

        }

    }

    static class IntegerUtils {
        public static long[][] generateBinomialCoefficients(int n) {
            long[][] result = new long[n + 1][n + 1];
            for (int i = 0; i <= n; i++) {
                result[i][0] = 1;
                for (int j = 1; j <= i; j++) {
                    result[i][j] = result[i - 1][j - 1] + result[i - 1][j];
                }
            }
            return result;
        }

    }

    static class OutputWriter {
        private final PrintWriter writer;

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

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

        public void print(Object... objects) {
            for (int i = 0; i < objects.length; i++) {
                if (i != 0) {
                    writer.print(' ');
                }
                writer.print(objects[i]);
            }
        }

        public void printLine(Object... objects) {
            print(objects);
            writer.println();
        }

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

    }
}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;

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

    static class TaskF {
        static boolean debug = true;
        int numberNumber;
        int t;
        long[][] bin = IntegerUtils.generateBinomialCoefficients(100);

        static {
            if (debug) {
                try {
                    FileOutputStream f = new FileOutputStream("file.txt");
                    System.setErr(new PrintStream(f));
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }

        public void solve(int testNumber, InputReader in, OutputWriter out) {
            numberNumber = in.readInt();
            t = in.readInt();

//        t = 1;

            //        HashMap<Integer, String> answers = new HashMap<>();
//
//        for (int i = 1, cnt = 0; cnt < 1e5; i++) {
//            int[] cntTake = new int[16];
//            for (char c : String.format("%x", i).toCharArray()) {
//                ++cntTake[Integer.parseInt("" + c, 16)];
//            }
//            boolean ok = true;
//            for (int c : cntTake) {
//                ok &= c <= t;
//            }
//            if (ok) {
//                ++cnt;
//                String answer = String.format("%x", i);
//                answers.put(cnt, answer);
//                System.err.println(cnt + " = " + answer);
//                System.err.flush();
//            }
//        }

//
//        for (int _numberNumber = 1; ; _numberNumber++) {
//            numberNumber = _numberNumber;
            int wordLength = 1;
            for (; ; wordLength++) {
                long[][] dp = new long[16][wordLength + 1];

                for (int length = 0; length <= wordLength; length++) {
                    for (int ch = 0; ch < 16; ch++) {
                        if (length == 0) {
                            dp[ch][length] = 1;
                        } else if (ch == 0) {
                            if (length <= t) {
                                dp[ch][length] = bin[wordLength - 1][length];
                            }
                        } else {
                            dp[ch][length] += dp[ch - 1][length];
                            for (int c = 1; c <= Math.min(length, t); c++) {
                                dp[ch][length] += bin[wordLength - length + c][c] * dp[ch - 1][length - c];
                            }
                        }
                    }
                }

                System.err.println("wordLength, dp: " + wordLength + " " + dp[15][wordLength]);
                System.err.flush();
                if (dp[15][wordLength] < numberNumber) {
                    numberNumber -= dp[15][wordLength];
                } else {
//                out.printLine("wordLength: " + wordLength);
                    break;
                }
            }

            StringBuilder ans = new StringBuilder();
            int[] maxCnt = new int[16];
            Arrays.fill(maxCnt, t);
            for (int pos = 0; pos < wordLength; pos++) {
                boolean addCh = false;
                for (int ch = 0; ch < 16; ch++) {
                    if (pos == 0 && ch == 0) {
                        continue;
                    }
                    if (maxCnt[ch] == 0) {
                        continue;
                    }
                    --maxCnt[ch];
                    long dp = getDp(wordLength - pos - 1, maxCnt);
                    if (numberNumber <= dp) {
                        ans.append(String.format("%x", ch));
                        addCh = true;
                        break;
                    } else {
                        ++maxCnt[ch];
                        numberNumber -= dp;
                    }
                }
                if (!addCh) {
                    throw new RuntimeException("no addCh");
//                    out.printLine("no add ch at pos=" + pos, "   : ", _numberNumber, answers.get(_numberNumber), ans);
//                    return;
                }
            }
//            if (!answers.get(_numberNumber).equals(ans.toString())) {
//                out.printLine("FUCK:", _numberNumber, answers.get(_numberNumber), ans);
//                return;
//            }
            out.printLine(ans);
//        }
        }

        private long getDp(int wordLength, int[] maxCnt) {
            long[][] dp = new long[16][wordLength + 1];
            for (int length = 0; length <= wordLength; length++) {
                for (int ch = 0; ch < 16; ch++) {
                    if (length == 0) {
                        dp[ch][length] = 1;
                    } else {
                        if (ch != 0) {
                            dp[ch][length] += dp[ch - 1][length];
                        }
                        for (int cnt = 1; cnt <= Math.min(length, maxCnt[ch]); cnt++) {
                            if (ch == 0) {
                                if (length == cnt) {
                                    dp[ch][length] += bin[wordLength][cnt];
                                }
                            } else {
                                dp[ch][length] += bin[wordLength - length + cnt][cnt] * dp[ch - 1][length - cnt];
                            }
                        }
                    }
                }
            }
            return dp[15][wordLength];
        }

    }

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

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

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

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

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

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

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

        }

    }

    static class IntegerUtils {
        public static long[][] generateBinomialCoefficients(int n) {
            long[][] result = new long[n + 1][n + 1];
            for (int i = 0; i <= n; i++) {
                result[i][0] = 1;
                for (int j = 1; j <= i; j++) {
                    result[i][j] = result[i - 1][j - 1] + result[i - 1][j];
                }
            }
            return result;
        }

    }

    static class OutputWriter {
        private final PrintWriter writer;

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

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

        public void print(Object... objects) {
            for (int i = 0; i < objects.length; i++) {
                if (i != 0) {
                    writer.print(' ');
                }
                writer.print(objects[i]);
            }
        }

        public void printLine(Object... objects) {
            print(objects);
            writer.println();
        }

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

    }
}


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

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

    static class TaskF {
        int LEN;
        static final int DIGIT = 17;
        static int[] cnt = new int[DIGIT - 1];
        char[] res;
        int k;

        public void solve(int testNumber, InputReader in, PrintWriter out) {
            k = in.nextInt();
            int T = in.nextInt();
            Arrays.fill(cnt, T);

            if (k < 16) {
                out.println(getChar(k));
                return;
            }

            long[] counts = dp(13);
            LEN = getLength(counts, k);

            res = new char[LEN];

            int startIndex = 0;
            if (LEN > 10) startIndex = brute();

            int[] curCount = new int[]{0};
            for (int i = 1; i <= LEN - startIndex; i++) {
                bruteForce(startIndex, cnt, res, i + startIndex, k, curCount);
            }

            out.println(res);
        }

        private int getLength(long[] counts, int k) {
            int LEN = 1;
            for (; LEN <= 13; LEN++) {
                if (LEN <= cnt[0] && k > counts[LEN] - 1) continue;
                else if (LEN > cnt[0] && k > counts[LEN]) continue;
                else break;
            }
            return LEN;
        }

        private int brute() {
            k -= dp(LEN)[LEN - 1];
            if (LEN - 1 <= cnt[0]) k++;
            int ret = 3;
            for (int i = 0; i < ret; i++) {
                int digit = getNextDigit(i == 0 ? 0 : -1);
                for (; digit < DIGIT - 1 && k > 0; digit = getNextDigit(digit)) {
                    cnt[digit]--;
                    int temp = (int) dp(LEN - i)[LEN - i - 1];
                    if (k > temp) {
                        k -= temp;
                        cnt[digit]++;
                        continue;
                    } else if (k == temp) {
                        res[i++] = getChar(digit);
                        for (; i < LEN; i++) {
                            res[i] = getChar(getLastDigit());
                        }
                        return i;
                    } else {
                        res[i] = getChar(digit);
                        break;
                    }
                }
            }
            return ret;
        }

        private void bruteForce(int index, int[] cnt, char[] res, int len, int max, int[] cur) {
            if (index == len) {
                cur[0]++;
                return;
            }
            for (int i = getNextDigit(index == 0 ? 0 : -1); i != 16; i = getNextDigit(i)) {
                cnt[i]--;
                if (cur[0] < max) {
                    res[index] = getChar(i);
                    bruteForce(index + 1, cnt, res, len, max, cur);
                    cnt[i]++;
                } else return;
            }
        }

        private int getNextDigit(int startDigit) {
            int i = startDigit + 1;
            for (; i < cnt.length && cnt[i] == 0; i++) ;
            return i;
        }

        private long[] dp(int len) {
            long[][] dp = new long[DIGIT][++len];
            dp[0][0] = 1;

            for (int i = 1; i < DIGIT; ++i) {
                for (int j = 0; j < len; ++j) {
                    for (int c = 0; c <= Math.min(j, cnt[i - 1]); c++) {
                        for (int k = i - 1; k < i; k++) {
                            dp[i][j] += dp[k][j - c] * comb(j, c);
                        }
                    }
                }
            }

//        System.out.printf("dp[15][%d]: ", len);   print(dp[DIGIT - 1]);

            return dp[DIGIT - 1];
        }

        private char getChar(int digit) {
            return (char) (digit < 10 ? '0' + digit : 'a' + digit - 10);
        }

        private int getLastDigit() {
            int i;
            for (i = cnt.length - 1; i >= 0 && cnt[i] == 0; i--) ;
            cnt[i]--;
            return i;
        }

        private long comb(int n, int k) {
            long res = 1L;
            if (k < n)
                for (int i = 1; i <= k; i++) {
                    res = res * (n - k + i) / i;
                }
            return res;
        }

    }

    static class InputReader extends BufferedReader {
        StringTokenizer tokenizer;

        public InputReader(InputStream inputStream) {
            super(new InputStreamReader(inputStream), 32768);
        }

        public InputReader(String filename) {
            super(new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream(filename)));
        }

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

        public Integer nextInt() {
            return Integer.valueOf(next());
        }

    }
}


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

public class F {

	BufferedReader br;
	PrintWriter out;
	StringTokenizer st;
	boolean eof;

	static final int K = 110;
	static final int N = 500_000;

	double[][] dp = new double[N][K];
	int[] par = new int[N];

	void solve() throws IOException {
		int q = nextInt();

		for (int i = 0; i < N; i++)
			Arrays.fill(dp[i], 1);

		par[0] = -1;

		int curV = 1;

		while (q-- > 0) {
			int type = nextInt();
			int v = nextInt() - 1;
			if (type == 2) {
				double ret = 0;
				double[] ds = dp[v];
				for (int i = 0; i < ds.length; i++) {
					double prob = ds[i];
					ret += 1 - prob;
				}
				out.println(ret);
			} else {
				int u = curV++;
				par[u] = v;

				double old = dp[v][0];
				dp[v][0] *= 0.5;
				v = par[v];
				u = par[u];
				int k = 1;
				while (k < K && v != -1) {

					double nextOld = dp[v][k];
					dp[v][k] /= 0.5 * (1 + old);
					dp[v][k] *= 0.5 * (1 + dp[u][k - 1]);

					k++;
					v = par[v];
					u = par[u];
					old = nextOld;
				}

			}
		}
	}

	F() throws IOException {
		br = new BufferedReader(new InputStreamReader(System.in));
		out = new PrintWriter(System.out);
		solve();
		out.close();
	}

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

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

	String nextString() {
		try {
			return br.readLine();
		} catch (IOException e) {
			eof = true;
			return null;
		}
	}

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

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

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


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

public class E {
	FastScanner in;
	PrintWriter out;

	int[] p;
	double[][] dpEqLess;
	double[][] dpEqLessMul;
	int maxK = 50;

	public void solve() throws IOException {
		int q = in.nextInt();
		dpEqLess = new double[maxK][q];
		for (int i = 0; i < maxK; i++) {
			dpEqLess[i][0] = 1;
		}
		p = new int[q];
		p[0] = -1;
		int cntV = 0;
		for (int i = 0; i < q; i++) {
			int type = in.nextInt();
			int v = in.nextInt() - 1;
			if (type == 1) {
				int u = ++cntV;
				p[u] = v;
				for (int j = 0; j < maxK; j++) {
					dpEqLess[j][u] = 1;
				}
				double prev = 1;
				for (int j = 0; j < maxK; j++) {
					double val = dpEqLess[j][v];
					val /= prev;
					prev = dpEqLess[j][v]*0.5 + 0.5;
					val *= (0.5 + 0.5*(j - 1 >= 0 ? dpEqLess[j - 1][u] : 0));
					dpEqLess[j][v] = val;

					v = p[v];
					u = p[u];
					if (v == -1) {
						break;
					}
				}
			} else {
				double res = 0;
				for (int j = 1; j < maxK; j++) {
					res += j * (dpEqLess[j][v] - dpEqLess[j - 1][v]);
				}
				out.println(res);
			}
		}
	}

	public void run() {
		try {
			in = new FastScanner();
			out = new PrintWriter(System.out);

			solve();

			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	class FastScanner {
		BufferedReader br;
		StringTokenizer st;

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

		String next() {
			while (st == null || !st.hasMoreTokens()) {
				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());
		}
	}

	public static void main(String[] arg) {
		new E().run();
	}
}


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

public class E {

    final int MAX = 85;

    double[][] prob;
    int[] parent;
    int n;

    public void solve() {
        int q = in.nextInt();
        int[] t = new int[q], v = new int[q];
        n = 1;
        for (int i = 0; i < q; i++) {
            t[i] = in.nextInt();
            v[i] = in.nextInt() - 1;
            if (t[i] == 1) {
                n++;
            }
        }

        parent = new int[n];
        parent[0] = -1;
        prob = new double[n][MAX];
        Arrays.fill(prob[0], 1);
        int last = 0;
        for (int i = 0; i < q; i++) {
            if (t[i] == 1) {
                last++;
                parent[last] = v[i];
            }
        }

        last = 0;
        for (int i = 0; i < q; i++) {
            if (t[i] == 1) {
                last++;
                addVertex(last);
            } else {
                double result = 0;
                double[] pr = prob[v[i]];
                for (int j = 0; j < MAX; j++) {
                    result += 1 - pr[j];
                }
                out.println(result);
            }
        }
    }

    private void addVertex(int v) {
        Arrays.fill(prob[v], 1);

        int p = parent[v];
        double last = 1;
        for (int i = 0; i < MAX; i++) {
            if (p == -1) {
                break;
            }
            double tmp = prob[p][i];
            prob[p][i] /= (0.5 + 0.5 * last);
            last = tmp;
            p = parent[p];
        }
        p = parent[v];

        last = 0;
        for (int i = 0; i < MAX; i++) {
            if (p == -1) {
                break;
            }
            prob[p][i] *= (0.5 + 0.5 * last);
            last = prob[p][i];
            p = parent[p];
        }
    }

    public void run() {
        in = new FastScanner();
        out = new PrintWriter(System.out);
        solve();
        out.close();
    }

    FastScanner in;
    PrintWriter out;

    class FastScanner {
        BufferedReader br;
        StringTokenizer st;

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

        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) {
                }
            }
            return st.nextToken();
        }

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

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

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

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


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

public class E {
	FastScanner in;
	PrintWriter out;

	int[] p;
	double[][] dpEqLess;
	double[][] dpEqLessMul;
	int maxK = 150;

	public void solve() throws IOException {
		int q = in.nextInt();
		dpEqLess = new double[maxK][q];
		for (int i = 0; i < maxK; i++) {
			dpEqLess[i][0] = 1;
		}
		p = new int[q];
		p[0] = -1;
		int cntV = 0;
		for (int i = 0; i < q; i++) {
			int type = in.nextInt();
			int v = in.nextInt() - 1;
			if (type == 1) {
				int u = ++cntV;
				p[u] = v;
				for (int j = 0; j < maxK; j++) {
					dpEqLess[j][u] = 1;
				}
				double prev = 1;
				for (int j = 0; j < maxK; j++) {
					double val = dpEqLess[j][v];
					val /= prev;
					prev = dpEqLess[j][v]*0.5 + 0.5;
					val *= (0.5 + 0.5*(j - 1 >= 0 ? dpEqLess[j - 1][u] : 0));
					dpEqLess[j][v] = val;

					v = p[v];
					u = p[u];
					if (v == -1) {
						break;
					}
				}
			} else {
				double res = 0;
				for (int j = 1; j < maxK; j++) {
					res += j * (dpEqLess[j][v] - dpEqLess[j - 1][v]);
				}
				out.println(res);
			}
		}
	}

	public void run() {
		try {
			in = new FastScanner();
			out = new PrintWriter(System.out);

			solve();

			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	class FastScanner {
		BufferedReader br;
		StringTokenizer st;

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

		String next() {
			while (st == null || !st.hasMoreTokens()) {
				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());
		}
	}

	public static void main(String[] arg) {
		new E().run();
	}
}


/**
 *
 * @author Eduardo M
 */
import java.util.Scanner;

public class SubestacoesModestas {

    public static void main(String[] args) {
        new SubestacoesModestas().solucao();
    }

    Scanner sc = new Scanner(System.in);
    int l, y, n, cont, tt, aux, cont1, i, j, k;
    char[] vet = new char[810];
    char[] g = new char[810];
    char[] vet1 = new char[810];
    int[] vet2 = new int[21000];
    int[] vet3 = new int[21000];
    int[][] mat = new int[21000][810];
    int[][] mat1 = new int[21000][10];
    int[][] met2 = new int[2100][21000];

    void solucao() {
        String ent = sc.next();
        String ent1 = sc.next();
        l = sc.nextInt();
        y = ent.length();
        n = ent1.length();
        for (i = 0; i < y; i++) {
            vet[i] = ent.charAt(i);
        }
        for (i = 0; i < n; i++) {
            vet1[i] = ent1.charAt(i);
        }
        cont = ++tt;
        g = vet;
        int tempAdd = cont;
        for (i = 0; g[i] != 0; i++) {
            if (mat1[tempAdd][g[i] - '0'] == 0) {
                mat1[tempAdd][g[i] - '0'] = ++tt;
            }
            tempAdd = mat1[tempAdd][g[i] - '0'];
        }
        g = vet1;
        tempAdd = cont;
        for (i = 0; g[i] != 0; i++) {
            if (mat1[tempAdd][g[i] - '0'] == 0) {
                mat1[tempAdd][g[i] - '0'] = ++tt;
            }
            tempAdd = mat1[tempAdd][g[i] - '0'];
        }
        if (y == n) {
            int veri = cont, veri1 = cont;
            for (i = 0; i < y; i++) {
                if (veri == veri1 && vet[i] != vet1[i]) {
                    for (int c = vet[i] + 1; c < vet1[i]; c++) {
                        if (mat1[veri][c - '0'] == 0) {
                            mat1[veri][c - '0'] = ++tt;
                        }
                        mat[mat1[veri][c - '0']][y - i - 1]++;
                    }
                } else if (veri != veri1) {
                    for (int temp = vet[i] + 1; temp < '0' + 10; temp++) {
                        if (mat1[veri][temp - '0'] == 0) {
                            mat1[veri][temp - '0'] = ++tt;
                        }
                        mat[mat1[veri][temp - '0']][y - i - 1]++;
                    }
                    for (int temp = '0' + (i == 0 ? 1 : 0); temp < vet1[i]; temp++) {
                        if (mat1[veri1][temp - '0'] == 0) {
                            mat1[veri1][temp - '0'] = ++tt;
                        }
                        mat[mat1[veri1][temp - '0']][y - i - 1]++;
                    }
                }
                veri = mat1[veri][vet[i] - '0'];
                veri1 = mat1[veri1][vet1[i] - '0'];
            }
            mat[veri][0]++;
            if (veri != veri1) {
                mat[veri1][0]++;
            }
        } else {
            int veri = cont, veri1 = cont;
            for (i = 0; i < y; i++) {
                for (int temp = vet[i] + 1; temp < '0' + 10; temp++) {
                    if (mat1[veri][temp - '0'] == 0) {
                        mat1[veri][temp - '0'] = ++tt;
                    }
                    mat[mat1[veri][temp - '0']][y - i - 1]++;
                }
                veri = mat1[veri][vet[i] - '0'];
            }
            for (i = 0; i < n; i++) {
                for (int temp = '0' + (i == 0 ? 1 : 0); temp < vet1[i]; temp++) {
                    if (mat1[veri1][temp - '0'] == 0) {
                        mat1[veri1][temp - '0'] = ++tt;
                    }
                    mat[mat1[veri1][temp - '0']][n - i - 1]++;
                }
                veri1 = mat1[veri1][vet1[i] - '0'];
            }
            mat[veri][0]++;
            mat[veri1][0]++;
            for (i = 1; i < 10; i++) {
                if (mat1[cont][i] == 0) {
                    mat1[cont][i] = ++tt;
                }
                for (j = y + 1; j < n; j++) {
                    mat[mat1[cont][i]][j - 1]++;
                }
            }
        }
        aux = cont1 = 0;
        vet2[cont1++] = cont;
        for (; aux < cont1; aux++) {
            int x = vet2[aux];
            for (i = 0; i < 10; i++) {
                if (mat1[x][i] != 0) {
                    if (x == cont) {
                        vet3[mat1[x][i]] = x;
                    } else {
                        vet3[mat1[x][i]] = vet3[x];
                        while (vet3[mat1[x][i]] != cont && mat1[vet3[mat1[x][i]]][i] == 0) {
                            vet3[mat1[x][i]] = vet3[vet3[mat1[x][i]]];
                        }
                        if (mat1[vet3[mat1[x][i]]][i] != 0) {
                            vet3[mat1[x][i]] = mat1[vet3[mat1[x][i]]][i];
                        }
                    }
                    vet2[cont1++] = mat1[x][i];
                }
            }
        }
        for (i = 1; i < cont1; i++) {
            int x = vet2[i];
            for (j = 0; j < n; j++) {
                mat[x][j] += mat[vet3[x]][j];
            }
        }
        for (i = 1; i <= tt; i++) {
            for (j = 1; j < n; j++) {
                mat[i][j] += mat[i][j - 1];
            }
        }
         for (i = 1; i <= tt; i++) {
            met2[0][i] = mat[i][0];
        }
        for (i = 1; i <= l; i++) {
            for (j = 1; j <= tt; j++) {
                for (k = 0; k < 10; k++) {
                    met2[i][j] = Math.max(met2[i][j], met2[i - 1][mat1[j][k]]);
                }
                met2[i][j] += mat[j][Math.min(i, n - 1)];
            }
        }
        System.out.println(met2[l][cont]);
        int TempResu = cont;
        for (i = l; i >= 1; i--) {
            int val = met2[i][TempResu] - mat[TempResu][Math.min(i, n - 1)];
            for (int lext = 0; lext < 10; lext++) {
                if (met2[i - 1][mat1[TempResu][lext]] == val) {
                    System.out.print(lext);
                    TempResu = mat1[TempResu][lext];
                    break;
                }
            }
        }

    }


**
 *
 * @author Eduardo M
 */
import java.util.Scanner;

public class SubestacoesModestas {

    /*
 * 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.
     */
    public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);
    int l, y, n, cont, tt=0, aux, cont1, i, j, k;
    char[] vet = new char[810];
    char[] g = new char[810];
    char[] vet1 = new char[810];
    int[] vet2 = new int[21000];
    int[] vet3 = new int[21000];
    int[][] mat = new int[21000][810];
    int[][] mat1 = new int[21000][10];
    int[][] met2 = new int[2100][21000];

        String ent = sc.next();
        String ent1 = sc.next();
        l = sc.nextInt();
        y = ent.length();
        n = ent1.length();
        for (i = 0; i < y; i++) {
            vet[i] = ent.charAt(i);
        }
        for (i = 0; i < n; i++) {
            vet1[i] = ent1.charAt(i);
        }
        cont = ++tt;
        g = vet;
        int tempAdd = cont;
        for (i = 0; g[i] != 0; i++) {
            if (mat1[tempAdd][g[i] - '0'] == 0) {
                mat1[tempAdd][g[i] - '0'] = ++tt;
            }
            tempAdd = mat1[tempAdd][g[i] - '0'];
        }
        g = vet1;
        tempAdd = cont;
        for (i = 0; g[i] != 0; i++) {
            if (mat1[tempAdd][g[i] - '0'] == 0) {
                mat1[tempAdd][g[i] - '0'] = ++tt;
            }
            tempAdd = mat1[tempAdd][g[i] - '0'];
        }
        if (y == n) {
            int veri = cont, veri1 = cont;
            for (i = 0; i < y; i++) {
                if (veri == veri1 && vet[i] != vet1[i]) {
                    for (int c = vet[i] + 1; c < vet1[i]; c++) {
                        if (mat1[veri][c - '0'] == 0) {
                            mat1[veri][c - '0'] = ++tt;
                        }
                        mat[mat1[veri][c - '0']][y - i - 1]++;
                    }
                } else if (veri != veri1) {
                    for (int temp = vet[i] + 1; temp < '0' + 10; temp++) {
                        if (mat1[veri][temp - '0'] == 0) {
                            mat1[veri][temp - '0'] = ++tt;
                        }
                        mat[mat1[veri][temp - '0']][y - i - 1]++;
                    }
                    for (int temp = '0' + (i == 0 ? 1 : 0); temp < vet1[i]; temp++) {
                        if (mat1[veri1][temp - '0'] == 0) {
                            mat1[veri1][temp - '0'] = ++tt;
                        }
                        mat[mat1[veri1][temp - '0']][y - i - 1]++;
                    }
                }
                veri = mat1[veri][vet[i] - '0'];
                veri1 = mat1[veri1][vet1[i] - '0'];
            }
            mat[veri][0]++;
            if (veri != veri1) {
                mat[veri1][0]++;
            }
        } else {
            int veri = cont, veri1 = cont;
            for (i = 0; i < y; i++) {
                for (int temp = vet[i] + 1; temp < '0' + 10; temp++) {
                    if (mat1[veri][temp - '0'] == 0) {
                        mat1[veri][temp - '0'] = ++tt;
                    }
                    mat[mat1[veri][temp - '0']][y - i - 1]++;
                }
                veri = mat1[veri][vet[i] - '0'];
            }
            for (i = 0; i < n; i++) {
                for (int temp = '0' + (i == 0 ? 1 : 0); temp < vet1[i]; temp++) {
                    if (mat1[veri1][temp - '0'] == 0) {
                        mat1[veri1][temp - '0'] = ++tt;
                    }
                    mat[mat1[veri1][temp - '0']][n - i - 1]++;
                }
                veri1 = mat1[veri1][vet1[i] - '0'];
            }
            mat[veri][0]++;
            mat[veri1][0]++;
            for (i = 1; i < 10; i++) {
                if (mat1[cont][i] == 0) {
                    mat1[cont][i] = ++tt;
                }
                for (j = y + 1; j < n; j++) {
                    mat[mat1[cont][i]][j - 1]++;
                }
            }
        }
        aux = cont1 = 0;
        vet2[cont1++] = cont;
        for (; aux < cont1; aux++) {
            int x = vet2[aux];
            for (i = 0; i < 10; i++) {
                if (mat1[x][i] != 0) {
                    if (x == cont) {
                        vet3[mat1[x][i]] = x;
                    } else {
                        vet3[mat1[x][i]] = vet3[x];
                        while (vet3[mat1[x][i]] != cont && mat1[vet3[mat1[x][i]]][i] == 0) {
                            vet3[mat1[x][i]] = vet3[vet3[mat1[x][i]]];
                        }
                        if (mat1[vet3[mat1[x][i]]][i] != 0) {
                            vet3[mat1[x][i]] = mat1[vet3[mat1[x][i]]][i];
                        }
                    }
                    vet2[cont1++] = mat1[x][i];
                }
            }
        }
        for (i = 1; i < cont1; i++) {
            int x = vet2[i];
            for (j = 0; j < n; j++) {
                mat[x][j] += mat[vet3[x]][j];
            }
        }
        for (i = 1; i <= tt; i++) {
            for (j = 1; j < n; j++) {
                mat[i][j] += mat[i][j - 1];
            }
        }
         for (i = 1; i <= tt; i++) {
            met2[0][i] = mat[i][0];
        }
        for (i = 1; i <= l; i++) {
            for (j = 1; j <= tt; j++) {
                for (k = 0; k < 10; k++) {
                    met2[i][j] = Math.max(met2[i][j], met2[i - 1][mat1[j][k]]);
                }
                met2[i][j] += mat[j][Math.min(i, n - 1)];
            }
        }
        System.out.println(met2[l][cont]);
        int TempResu = cont;
        for (i = l; i >= 1; i--) {
            int val = met2[i][TempResu] - mat[TempResu][Math.min(i, n - 1)];
            for (int lext = 0; lext < 10; lext++) {
                if (met2[i - 1][mat1[TempResu][lext]] == val) {
                    System.out.print(lext);
                    TempResu = mat1[TempResu][lext];
                    break;
                }
            }
        }

    }


**
 *
 * @author Eduardo M
 */
import java.util.Scanner;

public class Main {

    /*
 * 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.
     */
    public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);
    int l, y, n, cont, tt=0, aux, cont1, i, j, k;
    char[] vet = new char[810];
    char[] g = new char[810];
    char[] vet1 = new char[810];
    int[] vet2 = new int[21000];
    int[] vet3 = new int[21000];
    int[][] mat = new int[21000][810];
    int[][] mat1 = new int[21000][10];
    int[][] met2 = new int[2100][21000];

        String ent = sc.next();
        String ent1 = sc.next();
        l = sc.nextInt();
        y = ent.length();
        n = ent1.length();
        for (i = 0; i < y; i++) {
            vet[i] = ent.charAt(i);
        }
        for (i = 0; i < n; i++) {
            vet1[i] = ent1.charAt(i);
        }
        cont = ++tt;
        g = vet;
        int tempAdd = cont;
        for (i = 0; g[i] != 0; i++) {
            if (mat1[tempAdd][g[i] - '0'] == 0) {
                mat1[tempAdd][g[i] - '0'] = ++tt;
            }
            tempAdd = mat1[tempAdd][g[i] - '0'];
        }
        g = vet1;
        tempAdd = cont;
        for (i = 0; g[i] != 0; i++) {
            if (mat1[tempAdd][g[i] - '0'] == 0) {
                mat1[tempAdd][g[i] - '0'] = ++tt;
            }
            tempAdd = mat1[tempAdd][g[i] - '0'];
        }
        if (y == n) {
            int veri = cont, veri1 = cont;
            for (i = 0; i < y; i++) {
                if (veri == veri1 && vet[i] != vet1[i]) {
                    for (int c = vet[i] + 1; c < vet1[i]; c++) {
                        if (mat1[veri][c - '0'] == 0) {
                            mat1[veri][c - '0'] = ++tt;
                        }
                        mat[mat1[veri][c - '0']][y - i - 1]++;
                    }
                } else if (veri != veri1) {
                    for (int temp = vet[i] + 1; temp < '0' + 10; temp++) {
                        if (mat1[veri][temp - '0'] == 0) {
                            mat1[veri][temp - '0'] = ++tt;
                        }
                        mat[mat1[veri][temp - '0']][y - i - 1]++;
                    }
                    for (int temp = '0' + (i == 0 ? 1 : 0); temp < vet1[i]; temp++) {
                        if (mat1[veri1][temp - '0'] == 0) {
                            mat1[veri1][temp - '0'] = ++tt;
                        }
                        mat[mat1[veri1][temp - '0']][y - i - 1]++;
                    }
                }
                veri = mat1[veri][vet[i] - '0'];
                veri1 = mat1[veri1][vet1[i] - '0'];
            }
            mat[veri][0]++;
            if (veri != veri1) {
                mat[veri1][0]++;
            }
        } else {
            int veri = cont, veri1 = cont;
            for (i = 0; i < y; i++) {
                for (int temp = vet[i] + 1; temp < '0' + 10; temp++) {
                    if (mat1[veri][temp - '0'] == 0) {
                        mat1[veri][temp - '0'] = ++tt;
                    }
                    mat[mat1[veri][temp - '0']][y - i - 1]++;
                }
                veri = mat1[veri][vet[i] - '0'];
            }
            for (i = 0; i < n; i++) {
                for (int temp = '0' + (i == 0 ? 1 : 0); temp < vet1[i]; temp++) {
                    if (mat1[veri1][temp - '0'] == 0) {
                        mat1[veri1][temp - '0'] = ++tt;
                    }
                    mat[mat1[veri1][temp - '0']][n - i - 1]++;
                }
                veri1 = mat1[veri1][vet1[i] - '0'];
            }
            mat[veri][0]++;
            mat[veri1][0]++;
            for (i = 1; i < 10; i++) {
                if (mat1[cont][i] == 0) {
                    mat1[cont][i] = ++tt;
                }
                for (j = y + 1; j < n; j++) {
                    mat[mat1[cont][i]][j - 1]++;
                }
            }
        }
        aux = cont1 = 0;
        vet2[cont1++] = cont;
        for (; aux < cont1; aux++) {
            int x = vet2[aux];
            for (i = 0; i < 10; i++) {
                if (mat1[x][i] != 0) {
                    if (x == cont) {
                        vet3[mat1[x][i]] = x;
                    } else {
                        vet3[mat1[x][i]] = vet3[x];
                        while (vet3[mat1[x][i]] != cont && mat1[vet3[mat1[x][i]]][i] == 0) {
                            vet3[mat1[x][i]] = vet3[vet3[mat1[x][i]]];
                        }
                        if (mat1[vet3[mat1[x][i]]][i] != 0) {
                            vet3[mat1[x][i]] = mat1[vet3[mat1[x][i]]][i];
                        }
                    }
                    vet2[cont1++] = mat1[x][i];
                }
            }
        }
        for (i = 1; i < cont1; i++) {
            int x = vet2[i];
            for (j = 0; j < n; j++) {
                mat[x][j] += mat[vet3[x]][j];
            }
        }
        for (i = 1; i <= tt; i++) {
            for (j = 1; j < n; j++) {
                mat[i][j] += mat[i][j - 1];
            }
        }
         for (i = 1; i <= tt; i++) {
            met2[0][i] = mat[i][0];
        }
        for (i = 1; i <= l; i++) {
            for (j = 1; j <= tt; j++) {
                for (k = 0; k < 10; k++) {
                    met2[i][j] = Math.max(met2[i][j], met2[i - 1][mat1[j][k]]);
                }
                met2[i][j] += mat[j][Math.min(i, n - 1)];
            }
        }
        System.out.println(met2[l][cont]);
        int TempResu = cont;
        for (i = l; i >= 1; i--) {
            int val = met2[i][TempResu] - mat[TempResu][Math.min(i, n - 1)];
            for (int lext = 0; lext < 10; lext++) {
                if (met2[i - 1][mat1[TempResu][lext]] == val) {
                    System.out.print(lext);
                    TempResu = mat1[TempResu][lext];
                    break;
                }
            }
        }

    }


import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
       SubestaçõesModestas d = new SubestaçõesModestas();
       d.solucao();
    }

    Scanner sc = new Scanner(System.in);
    int  L, TamX, TamN, Cont, TT, aux, cont1,i,j,k, veri,veri2,AuxD;
    char[] vet = new char[810];
    char[] vet1 = new char[810];
    int[] vet2 = new int[21000];
    int[] vet3 = new int[21000];
    int[][] mat1 = new int[21000][810];
    int[][] mat2 = new int[21000][10];
    int[][] mat = new int[2100][21000];

    void solucao(){
        String tl = sc.next();
        String tr = sc.next();
        L= sc.nextInt();
        TamX = tl.length();
        TamN = tr.length();
        for( i = 0 ; i < TamX ; i++){
            vet[i] = tl.charAt(i);
        }
        for( i = 0 ; i < TamN ; i++){
            vet1[i] = tr.charAt(i);
        }
        Cont = ++TT;
        add(vet);
        add(vet1);
        if(TamX == TamN){
            veri = Cont;
            veri2 = Cont;
            for( i = 0 ; i < TamX ; i++){
                if( vet[i] != vet1[i]){
                    for(int temp = vet[i]+1 ; temp < vet1[i] ; temp++){
                        if(mat2[veri][temp-'0'] == 0){
                            mat2[veri][temp-'0'] = ++TT;
                        }
                        mat1[mat2[veri][temp-'0']][TamX-i-1]++;
                    }
                }
                else if(veri != veri2){
                    for(int temp = vet[i]+1 ; temp < '0'+10 ; temp++){
                        if(mat2[veri][temp-'0'] == 0){
                            mat2[veri][temp-'0'] = ++TT;
                        }
                        mat1[mat2[veri][temp-'0']][TamX-i-1]++;
                    }
                    for(int temp = '0'+ (i == 0 ? 1 : 0) ; temp < vet1[i] ; temp++){
                        if(mat2[veri2][temp-'0'] == 0){
                            mat2[veri2][temp-'0'] = ++TT;
                        }
                        mat1[mat2[veri2][temp-'0']][TamX-i-1]++;
                    }
                }
                veri = mat2[veri][vet[i]-'0'];
                veri2 = mat2[veri2][vet1[i]-'0'];
            }
            mat1[veri][0]++;
            if(veri != veri2){
                mat1[veri2][0]++;
            }
        }
        else{
            veri = Cont;
            veri2 = Cont;
            for( i = 0 ; i < TamX ; i++){
                for(int temp = vet[i]+1 ; temp < '0'+10 ; temp++){
                    if(mat2[veri][temp-'0'] == 0){
                        mat2[veri][temp-'0'] = ++TT;
                    }
                    mat1[mat2[veri][temp-'0']][TamX-i-1]++;
                }
                veri = mat2[veri][vet[i]-'0'];
            }
            for( i = 0 ; i < TamN ; i++){
                for(int temp = '0'+ (i == 0 ? 1 : 0) ; temp < vet1[i] ; temp++){
                    if(mat2[veri2][temp-'0'] == 0){
                        mat2[veri2][temp-'0'] = ++TT;
                    }
                    mat1[mat2[veri2][temp-'0']][TamN-i-1]++;
                }
                veri2 = mat2[veri2][vet1[i]-'0'];
            }
            mat1[veri][0]++;
            mat1[veri2][0]++;
            for( i = 1 ; i < 10 ; i++){
                if(mat2[Cont][i] == 0){
                    mat2[Cont][i] = ++TT;
                }
                for( j = TamX+1 ; j < TamN ; j++){
                    mat1[mat2[Cont][i]][j-1]++;
                }
            }
        }
        resolver();
        for( i = 1 ; i < cont1 ; i++){
             AuxD = vet2[i];
            for( j = 0 ; j < TamN ; j++){
                mat1[AuxD][j] += mat1[vet3[AuxD]][j];
            }
        }
        for( i = 1 ; i <= TT ; i++){
            for( j = 1 ; j < TamN ; j++){
                mat1[i][j] += mat1[i][j-1];
            }
        }
        resultado();
        sc.close();
    }
    void resultado(){
        for( i = 1 ; i <= TT ; i++){
            mat[0][i] = mat1[i][0];
        }
        for( i = 1 ; i <= L; i++){
            for( j = 1 ; j <= TT ; j++){
                for( k = 0 ; k < 10 ; k++){
                    mat[i][j] = Math.max(mat[i][j], mat[i-1][mat2[j][k]]);
                }
                mat[i][j] += mat1[j][Math.min(i, TamN-1)];
            }
        }
        System.out.println(mat[L][Cont]);
        AuxD = Cont;
        for( i = L; i >= 1 ; i--){
            int val = mat[i][AuxD]-mat1[AuxD][Math.min(i, TamN-1)];
            for(int next = 0 ; next < 10 ; next++){
                if(mat[i-1][mat2[AuxD][next]]==val){
                    System.out.print(next);
                    AuxD = mat2[AuxD][next];
                    break;
                }
            }
        }
    }
    void resolver(){
	aux=cont1;
       	cont1 = 0;
        vet2[cont1++] = Cont;
        for(; aux < cont1 ; aux++){
            AuxD = vet2[aux];
            for( i = 0 ; i < 10 ; i++){
                if(mat2[AuxD][i] != 0){
                    if(AuxD == Cont){
                        vet3[mat2[AuxD][i]] = AuxD;
                    }
                    else{
                        vet3[mat2[AuxD][i]] = vet3[AuxD];
                        while(vet3[mat2[AuxD][i]] != Cont && mat2[vet3[mat2[AuxD][i]]][i] == 0){
                            vet3[mat2[AuxD][i]] = vet3[vet3[mat2[AuxD][i]]];
                        }
                        if(mat2[vet3[mat2[AuxD][i]]][i] != 0){
                            vet3[mat2[AuxD][i]] = mat2[vet3[mat2[AuxD][i]]][i];
                        }
                    }
                    vet2[cont1++] = mat2[AuxD][i];
                }
            }
        }
        for( i = 0 ; i < 10 ; i++){
            if(mat2[Cont][i] == 0){
                mat2[Cont][i] = Cont;
            }
        }
        for( j = 1 ; j < cont1 ; j++){
            AuxD = vet2[j];
            for( i = 0 ; i < 10 ; i++){
                if(mat2[AuxD][i] == 0){
                    mat2[AuxD][i] = mat2[vet3[AuxD]][i];
                }
            }
        }
    }
    void add(char s[]){
        AuxD = Cont;
        for( i = 0 ; s[i] != 0  ; i++){
            if(mat2[AuxD][s[i]-'0'] == 0){
                mat2[AuxD][s[i]-'0'] = ++TT;
            }
            AuxD = mat2[AuxD][s[i]-'0'];
        }
    }

}


import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.Arrays;

public class CF1202F {
    public static void main(String[] args) throws Exception {
        boolean local = System.getProperty("ONLINE_JUDGE") == null;
        boolean async = false;

        Charset charset = Charset.forName("ascii");

        FastIO io = local ? new FastIO(new FileInputStream("D:\\DATABASE\\TESTCASE\\Code.in"), System.out, charset) : new FastIO(System.in, System.out, charset);
        Task task = new Task(io, new Debug(local));

        if (async) {
            Thread t = new Thread(null, task, "dalt", 1 << 27);
            t.setPriority(Thread.MAX_PRIORITY);
            t.start();
            t.join();
        } else {
            task.run();
        }

        if (local) {
            io.cache.append("\n\n--memory -- \n" + ((Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) >> 20) + "M");
        }

        io.flush();
    }

    public static class Task implements Runnable {
        final FastIO io;
        final Debug debug;
        int inf = (int) 1e8;
        double eps = 1e-8;

        public Task(FastIO io, Debug debug) {
            this.io = io;
            this.debug = debug;
        }

        @Override
        public void run() {
            solve();
        }

        public void solve() {
            int a = io.readInt();
            int b = io.readInt();
            int n = a + b;
            FloorDivisionOptimizer optimizer = new FloorDivisionOptimizer(n, 1, n);
            int sum = 0;
            while (optimizer.hasNext()) {
                int k = optimizer.next();

                int pr = Math.min(optimizer.r, n / k);
                int pl = Math.max(optimizer.l, (n + k) / (k + 1));

                int xb = (a + k) / (k + 1);
                int xt = a / k;
                if (xb > xt) {
                    continue;
                }

                pl = Math.max(pl, xb + (b + k) / (k + 1));
                pr = Math.min(pr, xt + b / k);

                if (xb + (double) b / (k + 1) > eps + (double) a / (k + 1) + (double) b / k) {
                    continue;
                }

                sum += Math.max(pr - pl + 1, 0);
//                if (pr - pl + 1 > 0)
//                    debug.debug("lr", pl + " <= " + pr);
            }

            io.cache.append(sum);
        }
    }

    /**
     * \sum_{i=1}^{limit}f(\lfloor n/i \rfloor)
     */
    public static class FloorDivisionOptimizer {
        int l;
        int r;
        int n;
        int limit;

        public FloorDivisionOptimizer(int n, int l, int limit) {
            this.n = n;
            this.l = 0;
            this.limit = limit;
            this.r = l - 1;
        }

        public boolean hasNext() {
            return r < limit;
        }

        public int next() {
            l = r + 1;
            r = n / (n / l);
            return n / l;
        }
    }

    public static class FastIO {
        public final StringBuilder cache = new StringBuilder(1 << 13);
        private final InputStream is;
        private final OutputStream os;
        private final Charset charset;
        private StringBuilder defaultStringBuf = new StringBuilder(1 << 13);
        private byte[] buf = new byte[1 << 13];
        private int bufLen;
        private int bufOffset;
        private int next;

        public FastIO(InputStream is, OutputStream os, Charset charset) {
            this.is = is;
            this.os = os;
            this.charset = charset;
        }

        public FastIO(InputStream is, OutputStream os) {
            this(is, os, Charset.forName("ascii"));
        }

        private int read() {
            while (bufLen == bufOffset) {
                bufOffset = 0;
                try {
                    bufLen = is.read(buf);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                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;
        }

        public long readLong() {
            int sign = 1;

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

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

        public double readDouble() {
            boolean sign = true;
            skipBlank();
            if (next == '+' || next == '-') {
                sign = next == '+';
                next = read();
            }

            long val = 0;
            while (next >= '0' && next <= '9') {
                val = val * 10 + next - '0';
                next = read();
            }
            if (next != '.') {
                return sign ? val : -val;
            }
            next = read();
            long radix = 1;
            long point = 0;
            while (next >= '0' && next <= '9') {
                point = point * 10 + next - '0';
                radix = radix * 10;
                next = read();
            }
            double result = val + (double) point / radix;
            return sign ? result : -result;
        }

        public String readString(StringBuilder builder) {
            skipBlank();

            while (next > 32) {
                builder.append((char) next);
                next = read();
            }

            return builder.toString();
        }

        public String readString() {
            defaultStringBuf.setLength(0);
            return readString(defaultStringBuf);
        }

        public int readLine(char[] data, int offset) {
            int originalOffset = offset;
            while (next != -1 && next != '\n') {
                data[offset++] = (char) next;
                next = read();
            }
            return offset - originalOffset;
        }

        public int readString(char[] data, int offset) {
            skipBlank();

            int originalOffset = offset;
            while (next > 32) {
                data[offset++] = (char) next;
                next = read();
            }

            return offset - originalOffset;
        }

        public int readString(byte[] data, int offset) {
            skipBlank();

            int originalOffset = offset;
            while (next > 32) {
                data[offset++] = (byte) next;
                next = read();
            }

            return offset - originalOffset;
        }

        public char readChar() {
            skipBlank();
            char c = (char) next;
            next = read();
            return c;
        }

        public void flush() throws IOException {
            os.write(cache.toString().getBytes(charset));
            os.flush();
            cache.setLength(0);
        }

        public boolean hasMore() {
            skipBlank();
            return next != -1;
        }
    }

    public static class Debug {
        private boolean allowDebug;

        public Debug(boolean allowDebug) {
            this.allowDebug = allowDebug;
        }

        public void assertTrue(boolean flag) {
            if (!allowDebug) {
                return;
            }
            if (!flag) {
                fail();
            }
        }

        public void fail() {
            throw new RuntimeException();
        }

        public void assertFalse(boolean flag) {
            if (!allowDebug) {
                return;
            }
            if (flag) {
                fail();
            }
        }

        private void outputName(String name) {
            System.out.print(name + " = ");
        }

        public void debug(String name, int x) {
            if (!allowDebug) {
                return;
            }

            outputName(name);
            System.out.println("" + x);
        }

        public void debug(String name, long x) {
            if (!allowDebug) {
                return;
            }
            outputName(name);
            System.out.println("" + x);
        }

        public void debug(String name, double x) {
            if (!allowDebug) {
                return;
            }
            outputName(name);
            System.out.println("" + x);
        }

        public void debug(String name, int[] x) {
            if (!allowDebug) {
                return;
            }
            outputName(name);
            System.out.println(Arrays.toString(x));
        }

        public void debug(String name, long[] x) {
            if (!allowDebug) {
                return;
            }
            outputName(name);
            System.out.println(Arrays.toString(x));
        }

        public void debug(String name, double[] x) {
            if (!allowDebug) {
                return;
            }
            outputName(name);
            System.out.println(Arrays.toString(x));
        }

        public void debug(String name, Object x) {
            if (!allowDebug) {
                return;
            }
            outputName(name);
            System.out.println("" + x);
        }

        public void debug(String name, Object... x) {
            if (!allowDebug) {
                return;
            }
            outputName(name);
            System.out.println(Arrays.deepToString(x));
        }
    }
}


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

public class CF1202F extends PrintWriter {
	CF1202F() { super(System.out, true); }
	Scanner sc = new Scanner(System.in);
	public static void main(String[] $) {
		CF1202F o = new CF1202F(); o.main(); o.flush();
	}

	void main() {
		int a = sc.nextInt();
		int b = sc.nextInt();
		if (a > b) {
			int tmp = a; a = b; b = tmp;
		}
		int ab = a + b;
		double x = (double) a / ab;
		int upper = 10000000;
		if (upper > ab)
			upper = ab;
		int ans = ab - upper;
		for (int cd = 2; cd <= upper; cd++) {
			int c = (int) (cd * x + 0.5);
			if (c == 0)
				continue;
			int d = cd - c;
			int k = a / c, l = b / d;
			if (k == l || k == l + 1 && a % c == 0 || k == l - 1 && b % d == 0)
				ans++;
		}
		println(ans);
	}
}


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

public class CF1202F extends PrintWriter {
	CF1202F() { super(System.out, true); }
	Scanner sc = new Scanner(System.in);
	public static void main(String[] $) {
		CF1202F o = new CF1202F(); o.main(); o.flush();
	}

	void main() {
		int a = sc.nextInt();
		int b = sc.nextInt();
		if (a > b) {
			int tmp = a; a = b; b = tmp;
		}
		int ab = a + b;
		double x = (double) a / ab;
		int upper = 10000000;
		if (upper > ab)
			upper = ab;
		int ans = ab - upper;
		for (int cd = 2; cd <= upper; cd++) {
			int c = (int) (cd * x + 0.5);
			if (c == 0)
				c = 1;
			int d = cd - c;
			int k = a / c, l = b / d;
			if (k == l || k == l + 1 && a % c == 0 || k == l - 1 && b % d == 0)
				ans++;
		}
		println(ans);
	}
}


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

public class CF1202F extends PrintWriter {
	CF1202F() { super(System.out, true); }
	Scanner sc = new Scanner(System.in);
	public static void main(String[] $) {
		CF1202F o = new CF1202F(); o.main(); o.flush();
	}

	void main() {
		int a = sc.nextInt();
		int b = sc.nextInt();
		if (a > b) {
			int tmp = a; a = b; b = tmp;
		}
		int ab = a + b;
		double x = (double) a / ab;
		int ans = 0;
		for (int cd = 2; cd <= ab; cd++) {
			int c = (int) (cd * x + 0.5);
			if (c == 0)
				continue;
			int d = cd - c;
			int k = a / c, l = b / d;
			if (k == l || k == l + 1 && a % c == 0 || k == l - 1 && b % d == 0)
				ans++;
		}
		println(ans);
	}
}


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StreamTokenizer;

public class D {
    private static StreamTokenizer in;
    private static PrintWriter out;
    private static BufferedReader inB;

    private static int nextInt() throws Exception{
        in.nextToken();
        return (int)in.nval;
    }

    private static String nextString() throws Exception{
        in.nextToken();
        return in.sval;
    }

    static{
        in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
        inB = (new BufferedReader(new InputStreamReader(System.in)));
        out = new PrintWriter(System.out);
    }

    public static void main(String[] args)throws Exception{
        String[] s = inB.readLine().split(" ");
        int n = bitmas.n = Integer.parseInt(s[0]);
        int m = bitmas.m = Integer.parseInt(s[1]);
        int k = Integer.parseInt(s[2]);

        bitmas.nsize = n;
        bitmas.msize = (m)%32 == 0 ? (m/32) : (m/32 + 1);
        bitmas.size = bitmas.nsize * bitmas.msize;

        boolean[][] mas = new boolean[n][m];

        boolean[][] emas = new boolean[n][m];

        for(int i = 0; i<n; i++) {
            char[] c = inB.readLine().toCharArray();
            for(int j = 0; j<c.length; j++) {
                char ch = c[j];
                mas[i][j] = (ch == '#')?false:true;
                emas[i][j] = (ch == 'E')?true:false;
            }
        }

        boolean[][] masU = new boolean[n][m];
        boolean[][] masD = new boolean[n][m];
        boolean[][] masL = new boolean[n][m];
        boolean[][] masR = new boolean[n][m];

        for(int i = 0; i<n; i++) {
            for(int j = 0; j<m; j++) {
                masU[i][j] = (mas[i][j] && i>0   && !mas[i-1][j]) ? true : false;
                masD[i][j] = (mas[i][j] && i<n-1 && !mas[i+1][j]) ? true : false;
                masL[i][j] = (mas[i][j] && j>0   && !mas[i][j-1]) ? true : false;
                masR[i][j] = (mas[i][j] && i<m-1 && !mas[i][j+1]) ? true : false;
            }
        }

        bitmas T = new bitmas(), E = new bitmas(), Up1 = new bitmas(), Up2, Down1 = new bitmas(),
            Down2, Left1 = new bitmas(), Left2, Right1 = new bitmas(), Right2;

        T.set(mas);
        E.set(emas);
        Up1.set(masU);
        Down1.set(masD);
        Left1.set(masL);
        Right1.set(masR);

        Up2    = (T.XOR(Up1));
        Down2  = (T.XOR(Down1));
        Left2  = (T.XOR(Left1));
        Right2 = (T.XOR(Right1));

        char[] str = inB.readLine().toCharArray();

        if(T.equals(E)) {
            System.out.println(0);
            return;
        }
        for(int i = 0; i<k; i++) {
            switch(str[i]) {
            case 'U':
                T = (T.AND(Up1)).OR(((T.AND(Up2)).shiftUp()));
                break;
            case 'D':
                T = (T.AND(Down1)).OR(((T.AND(Down2)).shiftDown()));
                break;
            case 'L':
                T = (T.AND(Left1)).OR(((T.AND(Left2)).shiftRight()));
                break;
            case 'R':
                T = (T.AND(Right1)).OR(((T.AND(Right2)).shiftLeft()));
                break;
            }
//          T.print();
            if(T.equals(E)) {
                System.out.println((i+1));
                return;
            }
        }

        System.out.println(-1);
    }
}

class bitmas {
    int[][] mas;

    static int n=0,m=0,nsize=0,msize=0,size=0;

    bitmas() {
        mas = new int[nsize][msize];
    }

    void OutputBinary(int a) {
        for (int i = 0; i < 32; i++) {
            System.out.print(((a >> i) & 1));
        }
    }

    void print() {
        for(int i = 0; i<nsize; i++) {
            for(int j = 0; j<msize; j++) {
                OutputBinary(mas[i][j]);
            }
            System.out.println();
        }
        System.out.println();
    }

    void set(boolean[][] masNew) {
        for(int i = 0; i<n; i++) {
            for(int j = 0; j<m; j++) {
                int jj = j / 32;
                int k = j%32;
                mas[i][jj] |= (((masNew[i][j])?1:0)<<k );
            }
        }
    }

    bitmas OR(bitmas b) {
        bitmas ans = new bitmas();
        for(int i = 0; i<nsize; i++) {
            for(int j = 0; j<msize; j++) {
                ans.mas[i][j] = b.mas[i][j] | mas[i][j];
            }
        }
        return ans;
    }

    bitmas AND(bitmas b) {
        bitmas ans = new bitmas();
        for(int i = 0; i<nsize; i++) {
            for(int j = 0; j<msize; j++) {
                ans.mas[i][j] = b.mas[i][j] & mas[i][j];
            }
        }
        return ans;
    }

    bitmas XOR(bitmas b) {
        bitmas ans = new bitmas();
        for(int i = 0; i<nsize; i++) {
            for(int j = 0; j<msize; j++) {
                ans.mas[i][j] = b.mas[i][j] ^ mas[i][j];
            }
        }
        return ans;
    }

    boolean equals(bitmas b) {
        for(int i = 0; i<nsize; i++) {
            for(int j = 0; j<msize; j++) {
                if(mas[i][j] != b.mas[i][j])return false;
            }
        }
        return true;
    }

    bitmas shiftLeft() {
        for(int i = 0; i<nsize; i++) {
            int take = 0;
            for(int j = msize - 1; j>=0; j--) {

                int need = (1 << 31) & mas[i][j];
                mas[i][j] <<= 1;
                mas[i][j] |= take;
                take = need > 0 ? 1 : 0;
            }
        }
        return this;
    }

    bitmas shiftRight() {
        for(int i = 0; i<nsize; i++) {
            int take = 0;
            for(int j = 0; j<msize; j++) {

                int need = 1 & mas[i][j];
                mas[i][j] >>= 1;
                mas[i][j] |= (take << 31);
                take = need > 0 ? (1 << 31) : 0;
            }
        }
        return this;
    }

    bitmas shiftDown() {
        for(int j = 0; j<msize; j++) {
            int take = 0;
            for(int i = 0; i<nsize; i++) {
                int last = (mas[i][j]);
                mas[i][j] = take;
                take = last;
            }
        }

        return this;
    }

    bitmas shiftUp() {
        for(int j = 0; j<msize; j++) {
            int take = 0;
            for(int i = nsize - 1; i>=0; i--) {
                int last = (mas[i][j]);
                mas[i][j] = take;
                take = last;
            }
        }

        return this;
    }
}


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

public class D implements Runnable {

	static class BitSet {
		static final int MOD = 63;
		long [] a;

		BitSet(int n) {
			a = new long[(n >> 6) + 1];
		}

		BitSet(long [] a) {
			this.a = a;
		}

		void set(int bit) {
			int i = bit >> 6;
			a[i] |= 1L << (bit & MOD);
		}

		boolean isSet(int bit) {
			return (a[bit >> 6] & (1L << (bit & MOD))) != 0;
		}

		boolean isEmpty() {
			for (int i = 0; i < a.length; i++) {
				if (a[i] != 0) {
					return false;
				}
			}
			return true;
		}

		int size() {
			int ret = 0;
			for (int i = 0; i < a.length; i++) {
				ret += Long.bitCount(a[i]);
			}
			return ret;
		}

		public BitSet clone() {
			long [] na = new long[a.length];
			System.arraycopy(a, 0, na, 0, a.length);
			return new BitSet(na);
		}

		static long [] tmp = new long[3];

		void shiftLeft(long [] a) {
			for (int i = 0; i < a.length; i++) {
				tmp[i] = a[i] >>> 1;
				if (i < a.length - 1) {
					tmp[i] |= (a[i + 1] & 1) << 63;
				}

			}
		}

		void shiftRight(long [] a) {
			tmp[0] = 0;
			for (int i = 0; i < a.length; i++) {
				tmp[i] = a[i] << 1;
				if (i < a.length - 1) {
					tmp[i + 1] |= (a[i] & (1L << MOD)) >>> MOD;
				}
			}
		}

		void moveRight(long [] row, long [] notL) {
			shiftRight(a);
			for (int i = 0; i < a.length; i++) {
				a[i] = (tmp[i] & row[i]) | (a[i] & notL[i]);
			}
		}

		void moveLeft(long [] row, long [] notR) {
			shiftLeft(a);
			for (int i = 0; i < a.length; i++) {
				a[i] = (tmp[i] & row[i]) | (a[i] & notR[i]);
			}
		}

		void moveUp(long [] row, long [] weLow, long [] notUp) {
			for (int i = 0; i < a.length; i++) {
				a[i] = (row[i] & weLow[i]) | (a[i] & notUp[i]);
			}
		}

		void moveDown(long [] row, long [] weUp, long [] notLow) {
			for (int i = 0; i < a.length; i++) {
				a[i] = (row[i] & weUp[i]) | (a[i] & notLow[i]);
			}
		}
	}

	int exitX, exitY;

	void solve() throws Exception {
		int n = nextInt(), m = nextInt(), k = nextInt();
		BitSet [][] row = new BitSet[2][n];
		BitSet [][] rowL = new BitSet[2][n];
		BitSet [][] rowR = new BitSet[2][n];
		for (int i = 0; i < n; i++) {
			for (int q = 0; q < 2; q++) {
				row[q][i] = new BitSet(m);
				rowL[q][i] = new BitSet(m);
				rowR[q][i] = new BitSet(m);
			}
			char [] b = nextToken().toCharArray();
			for (int j = 0; j < m; j++) {
				int q = b[j] == '#' ? 1 : 0;
				row[q][i].set(j);
				if (j < m - 1) rowR[q][i].set(j + 1);
				if (j > 0) rowL[q][i].set(j - 1);
				if (b[j] == 'E') {
					exitX = j;
					exitY = i;
				}
			}
		}

		BitSet [] we = new BitSet[n];
		for (int i = 0; i < n; i++) {
			we[i] = (BitSet)row[0][i].clone();
		}

		char [] seq = nextToken().toCharArray();
		for (int step = 0; step < seq.length; step++) {
			char c = seq[step];
     			if (c == 'R') {
     				for (int i = 0; i < n; i++) {
     					we[i].moveRight(row[0][i].a, rowL[1][i].a);
     				}
     			}
     			if (c == 'L') {
     				for (int i = 0; i < n; i++) {
     					we[i].moveLeft(row[0][i].a, rowR[1][i].a);
     				}
     			}
     			if (c == 'U') {
     				for (int i = 1; i < n - 1; i++) {
     					we[i].moveUp(row[0][i].a, we[i + 1].a, row[1][i - 1].a);
     				}
     			}
     			if (c == 'D') {
     				for (int i = n - 2; i > 0; i--) {
     					we[i].moveDown(row[0][i].a, we[i - 1].a, row[1][i + 1].a);
     				}
     			}

			boolean done = true;
			for (int i = 0; i < n; i++) {
    				if (i != exitY) {
    					if (!we[i].isEmpty()) {
    						done = false;
    						break;
    					}
    				} else {
    					if (!we[i].isSet(exitX) || !(we[i].size() == 1)) {
    						done = false;
    						break;
    					}
    				}
    			}
			if (done) {
				out.println(step + 1);
				return;
			}
		}
		out.println(-1);
	}

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

	public void run() {
		try {
			Locale.setDefault(Locale.US);
			in = new BufferedReader(new InputStreamReader(System.in));
			out = new PrintWriter(System.out);
			sTime();
			solve();
			debug("Time consumed: " + gTime());

			out.close();
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(1);
		}
	}

	StringTokenizer tokenizer = new StringTokenizer("");
	BufferedReader in;
	PrintWriter out;
	long time;

	void sTime() {
		time = System.currentTimeMillis();
	}

	long gTime() {
		return System.currentTimeMillis() - time;
	}

	void gMemory() {
		debug("Memory: " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1000 + " kb");
	}

	public void debug(Object o) {
		System.err.println(o);
	}

	boolean seekForToken() {
		while (!tokenizer.hasMoreTokens()) {
			String s = null;
			try {
				s = in.readLine();
			} catch (Exception e) {
				e.printStackTrace();
			}
			if (s == null)
				return false;
			tokenizer = new StringTokenizer(s);
		}
		return true;
	}

	String nextToken() {
		return seekForToken() ? tokenizer.nextToken() : null;
	}

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

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

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

	BigInteger nextBig() {
		return new BigInteger(nextToken());
	}
}