import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.NoSuchElementException;
import java.io.Writer;
import java.math.BigInteger;
import java.io.InputStream;

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

class TaskC {
    public void solve(int testNumber, InputReader in, OutputWriter out) {
		int[] qtyBits = new int[30];
		int[] qtyRequests = new int[30];
		int count = in.readInt();
		int requestCount = in.readInt();
		for (int i = 0; i < count; i++) {
			int cell = in.readInt();
			for (int j = 0; j < 30; j++) {
				if ((cell >> j & 1) == 1)
					qtyBits[j]++;
			}
		}
		for (int i = 0; i < requestCount; i++)
			qtyRequests[in.readInt()]++;
		int answer = 0;
		IntList weights = new IntArrayList();
		for (int i = 0; i < 30; i++) {
			for (int j = 0; j < qtyRequests[i]; j++)
				weights.add(1);
			for (int j = 0; j < weights.size() && j < qtyBits[i]; j++)
				answer += weights.get(j);
			IntList newWeights = new IntArrayList();
			for (int j = qtyBits[i]; j < weights.size(); j += 2) {
				int totalWeight = weights.get(j);
				if (j + 1 < weights.size())
					totalWeight += weights.get(j + 1);
				newWeights.add(totalWeight);
			}
			weights = newWeights;
		}
		out.printLine(answer);
    }
}

class InputReader {

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

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

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

	public 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);
	}
}

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();
	}

	}

abstract class IntList extends IntCollection implements Comparable<IntList> {
	private static final int INSERTION_THRESHOLD = 8;

	public abstract int get(int index);
	public abstract void set(int index, int value);

	public IntIterator iterator() {
		return new IntIterator() {
			private int size = size();
			private int index = 0;

			public int value() throws NoSuchElementException {
				if (!isValid())
					throw new NoSuchElementException();
				return get(index);
			}

			public void advance() throws NoSuchElementException {
				if (!isValid())
					throw new NoSuchElementException();
				index++;
			}

			public boolean isValid() {
				return index < size;
			}
		};
	}

	private void swap(int first, int second) {
		if (first == second)
			return;
		int temp = get(first);
		set(first, get(second));
		set(second, temp);
	}

	public IntSortedList inPlaceSort(IntComparator comparator) {
		quickSort(0, size() - 1, size(), comparator);
		return new IntSortedArray(this, comparator);
	}

	private void quickSort(int from, int to, int remaining, IntComparator comparator) {
		if (to - from < INSERTION_THRESHOLD) {
			insertionSort(from, to, comparator);
			return;
		}
		if (remaining == 0) {
			heapSort(from, to, comparator);
			return;
		}
		remaining >>= 1;
		int pivotIndex = (from + to) >> 1;
		int pivot = get(pivotIndex);
		swap(pivotIndex, to);
		int storeIndex = from;
		int equalIndex = to;
		for (int i = from; i < equalIndex; i++) {
			int value = comparator.compare(get(i), pivot);
			if (value < 0)
				swap(storeIndex++, i);
			else if (value == 0)
				swap(--equalIndex, i--);
		}
		quickSort(from, storeIndex - 1, remaining, comparator);
		for (int i = equalIndex; i <= to; i++)
			swap(storeIndex++, i);
		quickSort(storeIndex, to, remaining, comparator);
	}

	private void heapSort(int from, int to, IntComparator comparator) {
		for (int i = (to + from - 1) >> 1; i >= from; i--)
			siftDown(i, to, comparator, from);
		for (int i = to; i > from; i--) {
			swap(from, i);
			siftDown(from, i - 1, comparator, from);
		}
	}

	private void siftDown(int start, int end, IntComparator comparator, int delta) {
		int value = get(start);
		while (true) {
			int child = ((start - delta) << 1) + 1 + delta;
			if (child > end)
				return;
			int childValue = get(child);
			if (child + 1 <= end) {
				int otherValue = get(child + 1);
				if (comparator.compare(otherValue, childValue) > 0) {
					child++;
					childValue = otherValue;
				}
			}
			if (comparator.compare(value, childValue) >= 0)
				return;
			swap(start, child);
			start = child;
		}
	}

	private void insertionSort(int from, int to, IntComparator comparator) {
		for (int i = from + 1; i <= to; i++) {
			int value = get(i);
			for (int j = i - 1; j >= from; j--) {
				if (comparator.compare(get(j), value) <= 0)
					break;
				swap(j, j + 1);
			}
		}
	}

	public IntSortedList sort(IntComparator comparator) {
		return new IntArray(this).inPlaceSort(comparator);
	}

	public int hashCode() {
		int hashCode = 1;
		for (IntIterator i = iterator(); i.isValid(); i.advance())
			hashCode = 31 * hashCode + i.value();
		return hashCode;
	}

	public boolean equals(Object obj) {
		if (!(obj instanceof IntList))
			return false;
		IntList list = (IntList)obj;
		if (list.size() != size())
			return false;
		IntIterator i = iterator();
		IntIterator j = list.iterator();
		while (i.isValid()) {
			if (i.value() != j.value())
				return false;
			i.advance();
			j.advance();
		}
		return true;
	}

	public int compareTo(IntList o) {
		IntIterator i = iterator();
		IntIterator j = o.iterator();
		while (true) {
			if (i.isValid()) {
				if (j.isValid()) {
					if (i.value() != j.value()) {
						if (i.value() < j.value())
							return -1;
						else
							return 1;
					}
				} else
					return 1;
			} else {
				if (j.isValid())
					return -1;
				else
					return 0;
			}
			i.advance();
			j.advance();
		}
	}

	}

class IntArrayList extends IntList {
	private int[] array;
	private int size;

	public IntArrayList() {
		this(10);
	}

	public IntArrayList(int capacity) {
		array = new int[capacity];
	}

	public int get(int index) {
		if (index >= size)
			throw new IndexOutOfBoundsException();
		return array[index];
	}

	public void set(int index, int value) {
		if (index >= size)
			throw new IndexOutOfBoundsException();
		array[index] = value;
	}

	public int size() {
		return size;
	}

	public void add(int value) {
		ensureCapacity(size + 1);
		array[size++] = value;
	}

	private void ensureCapacity(int newCapacity) {
		if (newCapacity > array.length) {
			int[] newArray = new int[Math.max(newCapacity, array.length << 1)];
			System.arraycopy(array, 0, newArray, 0, size);
			array = newArray;
		}
	}

	}

abstract class IntCollection {
	public abstract IntIterator iterator();
	public abstract int size();
	public abstract void add(int value);

	}

interface IntIterator {
	public int value() throws NoSuchElementException;
	/*
	 * @throws NoSuchElementException only if iterator already invalid
	 */
	public void advance() throws NoSuchElementException;
	public boolean isValid();
}

interface IntComparator {
    public static final IntComparator DEFAULT = new IntComparator() {
        public int compare(int first, int second) {
            if (first < second)
                return -1;
            if (first > second)
                return 1;
            return 0;
        }
    };

	public int compare(int first, int second);
}

abstract class IntSortedList extends IntList {
	protected final IntComparator comparator;

	protected IntSortedList(IntComparator comparator) {
		this.comparator = comparator;
	}

	public void set(int index, int value) {
		throw new UnsupportedOperationException();
	}

	public void add(int value) {
		throw new UnsupportedOperationException();
	}

	public IntSortedList inPlaceSort(IntComparator comparator) {
		if (comparator == this.comparator)
			return this;
		throw new UnsupportedOperationException();
	}

	public IntSortedList sort(IntComparator comparator) {
		if (comparator == this.comparator)
			return this;
		return super.sort(comparator);
	}

	protected void ensureSorted() {
		int size = size();
		if (size == 0)
			return;
		int last = get(0);
		for (int i = 1; i < size; i++) {
			int current = get(i);
			if (comparator.compare(last, current) > 0)
				throw new IllegalArgumentException();
			last = current;
		}
	}

	}

class IntSortedArray extends IntSortedList {
	private final int[] array;

	public IntSortedArray(int[] array) {
		this(array, IntComparator.DEFAULT);
	}

	public IntSortedArray(IntCollection collection) {
		this(collection, IntComparator.DEFAULT);
	}

	public IntSortedArray(int[] array, IntComparator comparator) {
		super(comparator);
		this.array = array;
		ensureSorted();
	}

	public IntSortedArray(IntCollection collection, IntComparator comparator) {
		super(comparator);
		array = new int[collection.size()];
		int i = 0;
		for (IntIterator iterator = collection.iterator(); iterator.isValid(); iterator.advance())
			array[i++] = iterator.value();
		ensureSorted();
	}

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

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

class IntArray extends IntList {
	private final int[] array;

	public IntArray(int[] array) {
		this.array = array;
	}

	public IntArray(IntCollection collection) {
		array = new int[collection.size()];
		int i = 0;
		for (IntIterator iterator = collection.iterator(); iterator.isValid(); iterator.advance())
			array[i++] = iterator.value();
	}

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

	public void set(int index, int value) {
		array[index] = value;
	}

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

	public void add(int value) {
		throw new UnsupportedOperationException();
	}

	}


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

public class C {
	BufferedReader br;
	StringTokenizer in;
	PrintWriter out;

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

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

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

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

	public void solve() throws IOException {
		int n = nextInt();
		int m = nextInt();

		long[] cnt = new long[30];

		for (int i = 0; i < n; i++) {
			int z = nextInt();
			for (int j = 29; j >= 0; j--) {
				if (z >= 1 << j) {
					z -= 1 << j;
					cnt[j]++;
				}
			}
		}

		int[] c = new int[30];
		for (int i = 0; i < m; i++) {
			c[nextInt()]++;
		}

		int ans = 0;
		for (int i = 0; i < 30; i++) {
			boolean good = true;
			while (c[i] > 0) {
				int j = i;
				while (j < 30 && cnt[j] == 0) {
					j++;
				}

				if (j == 30) {
					good = false;
					break;
				}

				for (int k = j; k > i; k--) {
					cnt[k]--;
					cnt[k - 1] += 2;
				}

				cnt[i]--;
				ans++;
				c[i]--;
			}
			if (!good)
				break;
		}

		out.println(ans);
	}

	public void run() {
		try {
			br = new BufferedReader(new InputStreamReader(System.in));
			out = new PrintWriter(System.out);

			solve();

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

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


import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.NoSuchElementException;
import java.io.Writer;
import java.math.BigInteger;
import java.io.InputStream;

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

class TaskA {
    public void solve(int testNumber, InputReader in, OutputWriter out) {
		int count = in.readInt();
		int length = in.readInt();
		int time = in.readInt() * 2;
		int[] delta = IOUtils.readIntArray(in, count);
		double full = time / length;
		int remaining = time % length;
		double answer = full / 4 * (long)count * (count - 1);
		int j = 0;
		int lap = 0;
		int plus = 0;
		for (int i = 0; i < count; i++) {
			while (delta[j] + lap - delta[i] <= remaining) {
				j++;
				if (j == count) {
					j = 0;
					lap = length;
					plus = count;
				}
			}
			answer += (j - i + plus - 1) / 4d;
		}
		out.printLine(answer);
    }
}

class InputReader {

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

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

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

	public 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);
	}
}

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();
	}

	}

class IOUtils {

	public static int[] readIntArray(InputReader in, int size) {
		int[] array = new int[size];
		for (int i = 0; i < size; i++)
			array[i] = in.readInt();
		return array;
	}

	}


import java.util.*;

public class C {
	private static Scanner in;

	public void run() {
		int n = in.nextInt();
		int m = in.nextInt();
		int[] a = new int[n];
		for (int i = 0; i < n; i++) {
			a[i] = in.nextInt();
		}
		int[] b = new int[m];
		for (int i = 0; i < m; i++) {
			b[i] = in.nextInt();
		}
		Arrays.sort(a);
		Arrays.sort(b);
		int[] f = new int[31];
		for (int t = 0; t <= 30; t++) {
			for (int i = 0; i < n; i++) {
				if (((a[i] >> t) & 1) == 1) {
					f[t]++;
				}
			}
		}
		int lo = 0;
		int hi = m + 1;
		while (lo + 1 < hi) {
			int mid = (lo + hi) / 2;
			int[] d = new int[32];
			for (int i = 0; i < mid; i++) {
				d[b[i]]++;
			}
			for (int t = 0; t <= 30; t++) {
				d[t] -= f[t];
				if (d[t] > 0) {
					d[t + 1] += d[t];
				}
			}
			if (d[31] > 0) {
				hi = mid;
			} else {
				lo = mid;
			}
		}
		System.out.println(lo);
	}

	public static void main(String[] args) {
		Locale.setDefault(Locale.US);
		in = new Scanner(System.in);
		new C().run();
		in.close();
	}
}


import java.io.*;

public class Test {

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

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

    String readLine() {
        StringBuilder b = new StringBuilder();
        try {
            for (int c = 0; (c = System.in.read()) != -1; ) {
                if (c == '\n') {
                    break;
                } else {
                    b.append((char) (c));
                }
            }
        } catch (IOException e) {
        }
        return b.toString().trim();
    }

    static PrintWriter writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));

    long s;
    final int M = 60;
    long one = 1;
    long ans;
    long[][][] dp = new long[M][2*M][2];

    void start() {
        s = readLong();
        long base1 = 0;
        for (int h1 = 0; h1 < M; h1++) {
            base1 += one << h1;
            if (s < base1) break;

            long base2 = base1;
            for (int h2 = 0; h2 < M; h2++) {
                if (h2 > 0) base2 += one << h2;
                long ts = s - base2 - ((one << h2) - 1);
                if (ts < 0) break;
                ts %= base2;
                if (ts == 0) {
                    ans++;
                    continue;
                }
                for (int br = 1; br <= Math.max(0, h1 - 1) + Math.max(0, h2 - 1); br++) {
                    long sum = ts + br;
                    if ((sum & 1) != 0) continue;
                    int msb = Long.numberOfTrailingZeros(Long.highestOneBit(sum));
                    for (int i = 0; i <= msb; i++)
                        for (int j = 0; j <= br; j++)
                            for (int car = 0; car < 2; car++)
                                dp[i][j][car] = 0;
                    dp[0][0][0] = 1;
                    for (int i = 1; i <= msb; i++)
                        for (int j = 0; j <= br; j++)
                            for (int car = 0; car < 2; car++) {
                                if (dp[i-1][j][car] == 0) continue;
                                for (int b1 = 0; b1 < 2; b1++) {
                                    if (i > h1 - 1 && b1 > 0) continue;
                                    if (j + b1 > br) continue;
                                    for (int b2 = 0; b2 < 2; b2++) {
                                        if (i > h2 - 1 && b2 > 0) continue;
                                        if (j + b1 + b2 > br) continue;
                                        int s = car + b1 + b2;
                                        int ncar = s / 2;
                                        long val = s % 2;
                                        if ((sum & (1 << i)) != (val << i)) continue;
                                        dp[i][j + b1 + b2][ncar] += dp[i-1][j][car];
                                    }
                                }
                            }
                    ans += dp[msb][br][0];
                }
            }
        }
        writer.println(ans);
    }

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


import java.util.Arrays;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.InputStream;
import java.util.NoSuchElementException;
import java.io.OutputStreamWriter;
import java.math.BigInteger;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.io.IOException;

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

class TaskB {
    public void solve(int testNumber, MyScanner in, MyPrintWriter out) {
        int n=in.nextInt();
        String[] s = new String[n];
        int[] d = new int[n];
        for (int i = 0; i < n; i++) {
            d[i] = in.nextInt();
            s[i] = in.next();
        }
        int c = 0;
        for (int i=n-1;i>=0;i--) {
            if(s[i].equals("North")) {
                c += d[i];
            } else if(s[i].equals("South")) {
                c -= d[i];
            } else {
                if (c == 0 || c == 20000) {
                    out.println("NO");
                    return;
                }
            }
            if (c < 0 || c > 20000) {
                out.println("NO");
                return;
            }
        }
        out.println(c==0 ? "YES" : "NO");
    }
}

class MyScanner {
    private final InputStream in;

    public MyScanner(InputStream in) {
        this.in = in;
    }

    private static final int BUFSIZE = 65536;
    int bufLen;
    int bufPtr;
    byte[] buf = new byte[BUFSIZE];

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

    private char[] strBuf = new char[BUFSIZE];

    public String next() {
        int strLen = 0;
        int c;
        do {
            c = read();
            if (c == -1) throw new NoSuchElementException();
        } while (Character.isWhitespace(c));
        do {
            if (strLen + 1 >= strBuf.length) {
                char[] tmp = new char[strBuf.length * 2];
                System.arraycopy(strBuf, 0, tmp, 0, strBuf.length);
                strBuf = tmp;
            }
            strBuf[strLen++] = (char) c;
            c = read();
        } while (c != -1 && !Character.isWhitespace(c));
        return new String(strBuf, 0, strLen);
    }

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

}

class MyPrintWriter {
    PrintWriter out;

    public MyPrintWriter(OutputStream outputStream) {
        out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
    }

    public void println(Object... os) {
        if (os.length == 0) {
            out.println();
            return;
        }
        for (int i = 0; i < os.length - 1; i++) {
            out.print(os[i]);
            out.print(' ');
        }
        out.println(os[os.length - 1]);
    }

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

}


import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.util.NoSuchElementException;
import java.math.BigInteger;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.io.IOException;
import java.util.Arrays;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.util.Set;

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

class TaskG {

    long INF= (long) 1e17;
    public void solve(int testNumber, MyScanner in, MyPrintWriter out) {
        long s = in.nextLong();
        long res = 0;
        for (int l = 0; l <= 55; l++)
            for (int r = 0; r <= 55; r++) {
                long L=0,R=INF;
                while(R-L>1){
long min=0;
                    long max=0;
                    long m = (R+L)/2;

                    min += m;
                    long v=m*2;
                    for(int i=0;i<l;i++){
                        min = Math.min(min + v, INF);
                        v = Math.min(v * 2, INF);
                    }
                    v=m*2+1;
                    for(int i=0;i<r;i++){
                        min = Math.min(min + v, INF);
                        v = Math.min(v * 2, INF);
                    }

                    max += m;
                    v=m*2;
                    for(int i=0;i<l;i++){
                        max = Math.min(max + v, INF);
                        v = Math.min(v * 2 + 1, INF);
                    }
                    v=m*2+1;
                    for(int i=0;i<r;i++){
                        max = Math.min(max + v, INF);
                        v = Math.min(v * 2 + 1, INF);
                    }
                    if (s < min) {
                        R = m;
                    } else if (s > max) {
                        L = m;
                    } else {
                        res += solve(s - min,l,r);
                        break;
                    }
                }
            }
        out.println(res);
    }

    private long solve(long s, int l, int r) {
        l = Math.max(l-1, 0);
        r = Math.max(r-1, 0);
        long[] cand = new long[l + r];
        for(int i=0;i<l;i++)cand[i] = (1L << l) - 1;
        for(int i=0;i<r;i++)cand[l + i] = (1L << r) - 1;
        Arrays.sort(cand);
        HashMap<Long, Long> cur = new HashMap<>();
        cur.put(0L, 1L);
        for(int i=cand.length-1;i>=0;i--) {
            HashMap<Long, Long> nxt = new HashMap<>();
            long c = cand[i];
            long rest = 0;
            for(int j=0;j<i;j++)rest += cand[i];
            for(Map.Entry<Long, Long> e : cur.entrySet()) {
                long val = e.getKey();
                if (val + c <= s) {
                    if(!nxt.containsKey(val+c)){
                        nxt.put(val+c, 1L);
                    } else{
                        nxt.put(val+c, nxt.get(val+c) + 1);
                    }
                }
                if (val + rest >= s) {
                    if(!nxt.containsKey(val)){
                        nxt.put(val, 1L);
                    } else{
                        nxt.put(val, nxt.get(val) + 1);
                    }
                }
            }
            cur = nxt;
        }
        return cur.get(s);
    }

}

class MyScanner {
    private final InputStream in;

    public MyScanner(InputStream in) {
        this.in = in;
    }

    private static final int BUFSIZE = 65536;
    int bufLen;
    int bufPtr;
    byte[] buf = new byte[BUFSIZE];

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

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

}

class MyPrintWriter {
    PrintWriter out;

    public MyPrintWriter(OutputStream outputStream) {
        out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
    }

    public void println(Object... os) {
        if (os.length == 0) {
            out.println();
            return;
        }
        for (int i = 0; i < os.length - 1; i++) {
            out.print(os[i]);
            out.print(' ');
        }
        out.println(os[os.length - 1]);
    }

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

}


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

public class Main {

	Input in;
	PrintWriter out;

	final static int INF = (int) 1e9;
	final static int MOD = (int) 1e9 + 7;
	final static long LINF = (long) 1e18;
	final static double PI = (double) Math.acos(-1.0);
	final static double EPS = (double) 1e-9;

	void solve() {
		long x = in.nextLong();
		long ans = 0;
		for (int k = 0; k <= 50; k++) {
			for (int l = 0; l <= 50; l++) {
				long m = (1L << (k + 1)) + (1L << (l + 1)) - 3;
				long y = x - (1L << l) + 1;
				if (y < m) continue;
				for (int tot = 0; tot <= k + l; tot++) {
					long tmp = (y + tot) % m;
					if (tmp > (1L << k) + (1L << l) - 2) {
						continue;
					}
					int[] digit = new int[50];
					int cnt = 0;
					while (tmp > 0) {
						digit[cnt++] = (int) (tmp % 2);
						tmp >>= 1;
					}
					if (tot > 2 * cnt) continue;
					long[][][] dp = new long[cnt + 1][2 * cnt + 1][2];
					dp[0][0][0] = 1;
					for (int pos = 0; pos < cnt; pos++) {
						for (int sum = 0; sum <= tot; sum++) {
							for (int car = 0; car < 2; car++) if (dp[pos][sum][car] != 0) {
								int lox = 0, hix = 1;
								int loy = 0, hiy = 1;
								if (pos >= k || pos == 0) hix = 0;
								if (pos >= l || pos == 0) hiy = 0;
								for (int i = lox; i <= hix; i++) {
									for (int j = loy; j <= hiy; j++) {
										int u = i + j + car;
										if (u % 2 == digit[pos]) {
											dp[pos + 1][sum + i + j][u / 2] += dp[pos][sum][car];
										}
									}
								}
							}
						}
					}
					ans += dp[cnt][tot][0];
				}
			}
		}
		out.println(ans);
	}

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

	public void run() {
		in = new Input();
		try {
			out = new PrintWriter(System.out);
			//out = new PrintWriter(new FileWriter("a.out"));
		}
		catch (Exception ex) {
		}
		long stime = System.currentTimeMillis();
		solve();
		if (System.getProperty("ONLINE_JUDGE") == null) {
			out.println("\nTime elapsed: " + (System.currentTimeMillis() - stime) + "ms");
		}
		out.close();
	}

	public class Input {
		StringTokenizer token = null;
		BufferedReader in;
		public Input() {
			try {
				if (System.getProperty("ONLINE_JUDGE") == null) {
					in = new BufferedReader(new InputStreamReader(System.in));
					//in = new BufferedReader(new FileReader("in.txt"));
				}
				else {
					in = new BufferedReader(new InputStreamReader(System.in));
				}
			}
			catch (Exception ex) {
			}
		}
		int nextInt() {
			return Integer.parseInt(nextString());
		}
		long nextLong() {
			return Long.parseLong(nextString());
		}
		double nextDouble() {
			return Double.parseDouble(nextString());
		}
		String nextString() {
			try {
				while (token == null || !token.hasMoreTokens()) {
					token = new StringTokenizer(in.readLine());
				}
			}
			catch (IOException e) {
			}
			return token.nextToken();
		}
	}
}


import java.io.InputStreamReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.Writer;
import java.io.InputStream;

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

class TaskE {
//    static long[] F;
//    static final int N = 55;
//
//    static {
//        F = new long[N];
//        F[0] = 1;
//        for (int i = 1; i < N; i++) {
//            long bad = (1L << (i + 1 >> 1));
//            if ((i & 1) == 0) {
//                bad += (1L << (i >> 1));
//            }
//            F[i] = (((1L << i) - bad) >> 2) + (bad >> 1);
//        }
//    }

    static long getCountWithPrefix(int[] c, int prefix) {
        if (c[0] == '1') return 0;
        int n = c.length;
        long ans = 0;
//        System.out.println(Arrays.toString(c) + " " + prefix);
        for (int last = 0; last < 2; last++) {
            loop:
            for (int same = 1; same <= n; same++) {
                int[] cur = c.clone();
//                System.out.println("same = " + same);
                long ways = 1;
                for (int i = 0; i < same; i++) {
                    if (cur[i] < 0) {
                        cur[i] = 0;
                        ways *= 2;
                    }
                    int put = last ^ cur[i];
                    if (cur[n - i - 1] >= 0 && cur[n - i - 1] != put) continue loop;
                    cur[n - i - 1] = put;
                    if ((last ^ cur[i]) != cur[n - i - 1]) continue loop;
                }
                if (same == n) {
                    ans += ways;
//                    System.out.println(last + " " + same + " " + Arrays.toString(cur) + " " + ways);
                    continue;
                }
                if (cur[same] >= 0 && cur[same] != 0) continue;
                if (cur[n - same - 1] >= 0 && cur[n - same - 1] != (last ^ 1)) continue;
                cur[same] = 0;
                cur[n - same - 1] = (last ^ 1);
                for (int i = 0; i < n; i++) if (cur[i] < 0) ways *= 2;
                ans += ways;
//                System.out.println(last + " " + same + " " + Arrays.toString(cur) + " " + ways);
            }
        }
//        System.out.println("ans = " + ans);
        return ans;
    }

    public void solve(int testNumber, FastScanner in, FastPrinter out) {
        int n = in.nextInt();
        long k = in.nextLong();
        int[] ans = new int[n];
        Arrays.fill(ans, -1);
        ans[0] = 0;
        if (getCountWithPrefix(ans, 1) <= k) {
            out.println(-1);
            return;
        }
        for (int prefix = 1; prefix < n; prefix++) {
            boolean found = false;
            for (int put = 0; put < 2; put++) {
                ans[prefix] = put;
                long count = getCountWithPrefix(ans, prefix + 1);
                if (count <= k) {
                    k -= count;
                } else {
                    found = true;
                    break;
                }
            }
            if (!found) throw new AssertionError();
        }
        for (int i : ans) out.print(i);
        out.println();
    }
}

class FastScanner extends BufferedReader {

    public FastScanner(InputStream is) {
        super(new InputStreamReader(is));
    }

    public int read() {
        try {
            int ret = super.read();
//            if (isEOF && ret < 0) {
//                throw new InputMismatchException();
//            }
//            isEOF = ret == -1;
            return ret;
        } catch (IOException e) {
            throw new InputMismatchException();
        }
    }

    public String next() {
        StringBuilder sb = new StringBuilder();
        int c = read();
        while (isWhiteSpace(c)) {
            c = read();
        }
        if (c < 0) {
            return null;
        }
        while (c >= 0 && !isWhiteSpace(c)) {
            sb.appendCodePoint(c);
            c = read();
        }
        return sb.toString();
    }

    static boolean isWhiteSpace(int c) {
        return c >= 0 && c <= 32;
    }

    public int nextInt() {
        int c = read();
        while (isWhiteSpace(c)) {
            c = read();
        }
        int sgn = 1;
        if (c == '-') {
            sgn = -1;
            c = read();
        }
        int ret = 0;
        while (c >= 0 && !isWhiteSpace(c)) {
            if (c < '0' || c > '9') {
                throw new NumberFormatException("digit expected " + (char) c
                        + " found");
            }
            ret = ret * 10 + c - '0';
            c = read();
        }
        return ret * sgn;
    }

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

    public String readLine() {
        try {
            return super.readLine();
        } catch (IOException e) {
            return null;
        }
    }

}

class FastPrinter extends PrintWriter {

    public FastPrinter(OutputStream out) {
        super(out);
    }

    public FastPrinter(Writer out) {
        super(out);
    }

}


import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
import static java.util.Collections.*;
public class Main {
    public static void main(String[] args) {
    new Main().run();
    }
    void debug(Object...os){
    System.err.println(deepToString(os));
    }
    Scanner sc = new Scanner(System.in);
    void run(){
//  for (int i = 0; i<20; i++) {
//      survey(i);
//  }

    int n=sc.nextInt();
//  survey(n);
    long k=sc.nextLong();
    long res = solve(n,k);
    if(res==-1){
        System.out.println("-1");
    }else{
        String s=Long.toBinaryString(res);
        while(s.length()<n)s="0"+s;
        System.out.println(s);
    }
    }

    private long solve(int n,long k){
    boolean even=n%2==0;
    int sub = even ? 2:1;
    long have = 1L<<n/2;
    int first;
    for(first=0;first<1<<(n-1)/2;first++){
        if(k>=have)k-=have;
        else break;
        have-=sub;
    }
    if(first==(1<<(n-1)/2)){
        return -1;
    }
    int last;
    int msk=(1<<n/2)-1;
    for(last=0;;last++){
        assert last<(1L<<n/2);
        int rev = rev(last, n/2);
        if(rev<first || (msk^rev)<first)continue;
        if(k==0)break;
        k--;
    }

    return first<<n/2 | last;
    }

    int rev(int i,int n){
    return Integer.reverse(i)>>>32-n;
    }
    private int flip(int i, int n) {
    return (1<<n)-1 ^ i;
    }
    private void survey(int n) {
    boolean[] used=new boolean[1<<n];
    int cnt=0;
    for (int i = 0; i<1<<n; i++)if(!used[i]) {
        String s=Integer.toBinaryString(i);
        while(s.length()<n)s="0"+s;
        cnt++;
        System.out.println(s);
        used[i]=true;
        used[rev(i, n)]=true;
        used[flip(i,n)]=true;
        used[rev(flip(i,n),n)]=true;
    }
    System.out.println(cnt);
    }
}


import _007E.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
import static java.util.Collections.*;
public class Main {
    public static void main(String[] args) {
    new Main().run();
    }
    void debug(Object...os){
    System.err.println(deepToString(os));
    }
    Scanner sc = new Scanner(System.in);
    void run(){
    for (int i = 0; i<20; i++) {
//      survey(i);
    }

    int n=sc.nextInt();
//  survey(n);
    long k=sc.nextLong();
    long res = solve(n,k);
    if(res==-1){
        System.out.println("-1");
    }else{
        String s=Long.toBinaryString(res);
        while(s.length()<n)s="0"+s;
        System.out.println(s);
    }
    }

    private long solve(int n,long k){
    boolean even=n%2==0;
    int sub = even ? 2:1;
    long have = 1L<<n/2;
    int first;
    for(first=0;first<1<<(n-1)/2;first++){
        if(k>=have)k-=have;
        else break;
        have-=sub;
    }
    if(first==(1<<(n-1)/2)){
        return -1;
    }
    int last;
    int msk=(1<<n/2)-1;
    for(last=0;;last++){
        assert last<(1L<<n/2);
        int rev = rev(last, n/2);
        if(rev<first || (msk^rev)<first)continue;
        if(k==0)break;
        k--;
    }

    return first<<n/2 | last;
    }

    int rev(int i,int n){
    return Integer.reverse(i)>>>32-n;
    }
    private int flip(int i, int n) {
    return (1<<n)-1 ^ i;
    }
    private void survey(int n) {
    boolean[] used=new boolean[1<<n];
    int cnt=0;
    for (int i = 0; i<1<<n; i++)if(!used[i]) {
        String s=Integer.toBinaryString(i);
        while(s.length()<n)s="0"+s;
        cnt++;
        System.out.println(s);
        used[i]=true;
        used[rev(i, n)]=true;
        used[flip(i,n)]=true;
        used[rev(flip(i,n),n)]=true;
    }
    System.out.println(cnt);
    }
}


import _007E.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
import static java.util.Collections.*;
public class Main {
    public static void main(String[] args) {
    new Main().run();
    }
    void debug(Object...os){
    System.err.println(deepToString(os));
    }
    Scanner sc = new Scanner(System.in);
    void run(){
//  for (int i = 0; i<20; i++) {
//      survey(i);
//  }

    int n=sc.nextInt();
//  survey(n);
    long k=sc.nextLong();
    long res = solve(n,k);
    if(res==-1){
        System.out.println("-1");
    }else{
        String s=Long.toBinaryString(res);
        while(s.length()<n)s="0"+s;
        System.out.println(s);
    }
    }

    private long solve(int n,long k){
    boolean even=n%2==0;
    int sub = even ? 2:1;
    long have = 1L<<n/2;
    int first;
    for(first=0;first<1<<(n-1)/2;first++){
        if(k>=have)k-=have;
        else break;
        have-=sub;
    }
    if(first==(1<<(n-1)/2)){
        return -1;
    }
    int last;
    int msk=(1<<n/2)-1;
    for(last=0;;last++){
        assert last<(1L<<n/2);
        int rev = rev(last, n/2);
        if(rev<first || (msk^rev)<first)continue;
        if(k==0)break;
        k--;
    }

    return first<<n/2 | last;
    }

    int rev(int i,int n){
    return Integer.reverse(i)>>>32-n;
    }
    private int flip(int i, int n) {
    return (1<<n)-1 ^ i;
    }
    private void survey(int n) {
    boolean[] used=new boolean[1<<n];
    int cnt=0;
    for (int i = 0; i<1<<n; i++)if(!used[i]) {
        String s=Integer.toBinaryString(i);
        while(s.length()<n)s="0"+s;
        cnt++;
        System.out.println(s);
        used[i]=true;
        used[rev(i, n)]=true;
        used[flip(i,n)]=true;
        used[rev(flip(i,n),n)]=true;
    }
    System.out.println(cnt);
    }
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;

/**
 * @author Don Li
 */
public class UpgradingCities {

    int N = (int) 3e5 + 10;

    int n, m;
    int[][] G, R;

    boolean[] vis = new boolean[N];
    List<Integer> ord = new ArrayList<>();

    int[] dp = new int[N];
    int[] ep = new int[N];

    void solve() {
        n = in.nextInt(); m = in.nextInt();
        int[] fr = new int[m], to = new int[m];
        for (int i = 0; i < m; i++) {
            fr[i] = in.nextInt() - 1;
            to[i] = in.nextInt() - 1;
        }
        G = build_graph(n, fr, to);

        for (int i = 0; i < n; i++) {
            if (!vis[i]) {
                dfs(G, i);
            }
        }

        for (int u : ord) {
            dp[u] = 1;
            for (int v : G[u]) {
                dp[u] += dp[v];
            }
        }

        R = build_graph(n, to, fr);

        Arrays.fill(vis, false);
        for (int i = 0; i < n; i++) {
            if (!vis[i]) {
                dfs(R, i);
            }
        }

        for (int u : ord) {
            ep[u] = 1;
            for (int v : R[u]) {
                ep[u] += ep[v];
            }
        }

        int ans = 0;
        for (int i = 0; i < n; i++) if (dp[i] + ep[i] - 1 >= n - 1) ans++;
        out.println(ans);
    }

    void dfs(int[][] G, int u) {
        vis[u] = true;
        for (int v : G[u]) {
            if (!vis[v]) dfs(G, v);
        }
        ord.add(u);
    }

    int[][] build_graph(int n, int[] from, int[] to) {
        int[][] G = new int[n][];
        int[] cnt = new int[n];
        for (int i = 0; i < from.length; i++) {
            cnt[from[i]]++;
        }
        for (int i = 0; i < n; i++) G[i] = new int[cnt[i]];
        for (int i = 0; i < from.length; i++) {
            G[from[i]][--cnt[from[i]]] = to[i];
        }
        return G;
    }

    public static void main(String[] args) {
        in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)));
        out = new PrintWriter(System.out);
        new UpgradingCities().solve();
        out.close();
    }

    static FastScanner in;
    static PrintWriter out;

    static class FastScanner {
        BufferedReader in;
        StringTokenizer st;

        public FastScanner(BufferedReader in) {
            this.in = in;
        }

        public String nextToken() {
            while (st == null || !st.hasMoreTokens()) {
                try {
                    st = new StringTokenizer(in.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

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

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

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


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;

/**
 * @author Don Li
 */
public class UpgradingCities {

    int N = (int) 3e5 + 10;

    int n, m;
    int[][] G, R;

    boolean[] vis = new boolean[N];
    List<Integer> ord = new ArrayList<>();

    int[] dp = new int[N];
    int[] ep = new int[N];

    void solve() {
        n = in.nextInt(); m = in.nextInt();
        int[] fr = new int[m], to = new int[m];
        for (int i = 0; i < m; i++) {
            fr[i] = in.nextInt() - 1;
            to[i] = in.nextInt() - 1;
        }
        G = build_graph(n, fr, to);

        for (int i = 0; i < n; i++) {
            if (!vis[i]) {
                dfs(G, i);
            }
        }

        for (int u : ord) {
            dp[u] = 1;
            for (int v : G[u]) {
                dp[u] += dp[v];
            }
        }

        R = build_graph(n, to, fr);

        Arrays.fill(vis, false);
        ord.clear();
        for (int i = 0; i < n; i++) {
            if (!vis[i]) {
                dfs(R, i);
            }
        }

        for (int u : ord) {
            ep[u] = 1;
            for (int v : R[u]) {
                ep[u] += ep[v];
            }
        }

        int ans = 0;
        for (int i = 0; i < n; i++) if (dp[i] + ep[i] - 1 >= n - 1) ans++;
        out.println(ans);
    }

    void dfs(int[][] G, int u) {
        vis[u] = true;
        for (int v : G[u]) {
            if (!vis[v]) dfs(G, v);
        }
        ord.add(u);
    }

    int[][] build_graph(int n, int[] from, int[] to) {
        int[][] G = new int[n][];
        int[] cnt = new int[n];
        for (int i = 0; i < from.length; i++) {
            cnt[from[i]]++;
        }
        for (int i = 0; i < n; i++) G[i] = new int[cnt[i]];
        for (int i = 0; i < from.length; i++) {
            G[from[i]][--cnt[from[i]]] = to[i];
        }
        return G;
    }

    public static void main(String[] args) {
        in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)));
        out = new PrintWriter(System.out);
        new UpgradingCities().solve();
        out.close();
    }

    static FastScanner in;
    static PrintWriter out;

    static class FastScanner {
        BufferedReader in;
        StringTokenizer st;

        public FastScanner(BufferedReader in) {
            this.in = in;
        }

        public String nextToken() {
            while (st == null || !st.hasMoreTokens()) {
                try {
                    st = new StringTokenizer(in.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

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

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

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


import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
import java.lang.reflect.Array;
public class s{
	int to;
	int next_;
}
public class Main {

     static s edge[]=new s[601010];
     static int u[]=new int[601010];
     static int v[]=new int[601010];
     static int head[]=new int[601010];
     static int in[]=new int[601010];
	 static int n,m;
     static int cnt;
     static int count_[][]=new int[2][601010];
     public static void add(int u,int v)
     {
    	 edge[++cnt]=new s();
    	 edge[cnt].to=v;
    	 edge[cnt].next_=head[u];
    	 head[u]=cnt;
     }
     public static void f(int op)
     {
    	 Queue<Integer> q = new LinkedList<Integer>();
    	 int cn=0;
    	 for(int i=1;i<=n;i++)
    	 {
    		 if(in[i]==0)
    		 {
    		  //   if(op==0)
    		    //	 System.out.println(i+"*");
    			 q.offer(i);
                 cn++;
    		 }
    	 }
    	 while(q.peek()!=null)
    	 {
    		 int tm=q.poll();
    		 if(q.peek()==null)
    		 {
    			 count_[op][tm]=n-cn;
    		 }
    		 else if(q.size()==1)
    		 {
    			 int flag=0;
    			 for(int i=head[q.peek()];i!=-1;i=edge[i].next_)
    			 {
    				 int v=edge[i].to;
    				 if(in[v]==1)
    				 {
    					 flag=1;
    					 break;
    				 }
    			 }
    			 if(flag==1)
    				 count_[op][tm]=-n;
    			 else
    				 count_[op][tm]=n-cn;
    		 }
    		 else
    		 {
    			 count_[op][tm]=-n;
    		 }
    		 for(int i=head[tm];i!=-1;i=edge[i].next_)
    		 {
    			 int v=edge[i].to;
    			 in[v]--;
    			 if(in[v]==0)
    			 {
    				 q.offer(v);
    				 cn++;
    			 }
    		 }
    	 }
     }
	 public static void main(String[] args)
	 {
		 cnt=0;
		 Arrays.fill(head, -1);
		 Arrays.fill(in, 0);
		 Scanner cin=new Scanner(System.in);
		 n=cin.nextInt();
		 m=cin.nextInt();
		 for(int i=0;i<m;i++)
		 {
			 u[i]=cin.nextInt();
			 v[i]=cin.nextInt();
			 add(u[i],v[i]);
			 in[v[i]]++;
		 }
		 f(0);
		 cnt=0;
		 Arrays.fill(head, -1);
		 Arrays.fill(in, 0);
		 for(int i=0;i<m;i++)
		 {
			 add(v[i],u[i]);
             in[u[i]]++;
		 }
		 f(1);
		 int ans=0;
		 for(int i=1;i<=n;i++)
		 {
			// System.out.println(count_[0][i]+" "+count_[1][i]);
			 if(count_[0][i]+count_[1][i]>=n-2)
			 {
				 ans++;
			 }
		 }
		 System.out.println(ans);

	 }
}


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

/**
 * @author Don Li
 */
public class UpgradingCities {

    int N = (int) 3e5 + 10;

    int n, m;
    int[][] G, R;

    boolean[] vis = new boolean[N];
    int p;
    int[] ord;

    int[] d = new int[N];
    int[] prev = new int[N];

    int cnt;
    Stack<Integer> stack = new Stack<>();

    int[] dp = new int[N];
    int[] ep = new int[N];

    void solve() {
        n = in.nextInt(); m = in.nextInt();
        int[] fr = new int[m], to = new int[m];
        for (int i = 0; i < m; i++) {
            fr[i] = in.nextInt() - 1;
            to[i] = in.nextInt() - 1;
        }

        G = build_graph(n, fr, to);
        R = build_graph(n, to, fr);

        p = n;
        ord = new int[n];
        for (int i = 0; i < n; i++) {
            if (!vis[i]) {
                dfs(G, i);
            }
        }

        int last = -1;
        Arrays.fill(prev, -1);
        for (int u : ord) {
            d[u] = 1;
            for (int v : R[u]) {
                if (d[v] + 1 > d[u]) {
                    d[u] = d[v] + 1;
                    prev[u] = v;
                }
            }
            if (last < 0 || d[last] < d[u]) last = u;
        }

        int k = d[last];
        int[] path = new int[d[last]];
        while (last >= 0) {
            path[d[last] - 1] = last;
            last = prev[last];
        }

        boolean[] mark = new boolean[n];
        Map<Integer, Integer> map = new HashMap<>();
        L:
        for (int i = 0; i + 2 < k; i++) {
            map.clear();
            int u = path[i], v = path[i + 1], w = path[i + 2];
            for (int x : G[u]) {
                if (x != v) map.put(x, map.getOrDefault(x, 0) + 1);
            }
            for (int x : R[w]) {
                if (x != v) map.put(x, map.getOrDefault(x, 0) + 1);
            }
            int cand = -1;
            for (int x : map.keySet()) {
                if (map.get(x) == 2) {
                    if (cand == -1) cand = x;
                    else continue L;
                }
            }
            if (cand >= 0) mark[cand] = true;
        }
        if (k >= 2 && R[path[1]].length == 2) {
            for (int v : R[path[1]]) {
                if (v != path[0]) mark[v] = true;
            }
        }
        if (k >= 2 && G[path[k - 2]].length == 2) {
            for (int v : G[path[k - 2]]) {
                if (v != path[k - 1]) mark[v] = true;
            }
        }

        cnt = 0;
        Arrays.fill(vis, false);
        for (int i = k - 1; i >= 0; i--) {
            int u = path[i];
            dfs_cnt(G, u);
            dp[u] = cnt;
            for (int v : R[u]) {
                if (mark[v]) {
                    dfs_cnt2(G, v);
                    dp[v] = cnt;
                    while (!stack.isEmpty()) {
                        int x = stack.pop();
                        vis[x] = false;
                        cnt--;
                    }
                }
            }
        }
        for (int i = 0; i < n; i++) if (mark[i]) dp[i] = Math.max(dp[i], 1);

        cnt = 0;
        Arrays.fill(vis, false);
        for (int i = 0; i < k; i++) {
            int u = path[i];
            dfs_cnt(R, u);
            ep[u] = cnt;
            for (int v : G[u]) {
                if (mark[v]) {
                    dfs_cnt2(R, v);
                    ep[v] = cnt;
                    while (!stack.isEmpty()) {
                        int x = stack.pop();
                        vis[x] = false;
                        cnt--;
                    }
                }
            }
        }
        for (int i = 0; i < n; i++) if (mark[i]) ep[i] = Math.max(ep[i], 1);

        int ans = 0;
        for (int i = 0; i < n; i++) {
            if (dp[i] + ep[i] >= n) ans++;
        }
        out.println(ans);
    }

    void dfs_cnt2(int[][] G, int u) {
        vis[u] = true;
        cnt++;
        stack.push(u);
        for (int v : G[u]) {
            if (!vis[v]) dfs_cnt2(G, v);
        }
    }

    void dfs_cnt(int[][] G, int u) {
        vis[u] = true;
        cnt++;
        for (int v : G[u]) {
            if (!vis[v]) dfs_cnt(G, v);
        }
    }

    void dfs(int[][] G, int u) {
        vis[u] = true;
        for (int v : G[u]) {
            if (!vis[v]) dfs(G, v);
        }
        ord[--p] = u;
    }

    int[][] build_graph(int n, int[] from, int[] to) {
        int[][] G = new int[n][];
        int[] cnt = new int[n];
        for (int i = 0; i < from.length; i++) {
            cnt[from[i]]++;
        }
        for (int i = 0; i < n; i++) G[i] = new int[cnt[i]];
        for (int i = 0; i < from.length; i++) {
            G[from[i]][--cnt[from[i]]] = to[i];
        }
        return G;
    }

    public static void main(String[] args) {
        in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)));
        out = new PrintWriter(System.out);
        new UpgradingCities().solve();
        out.close();
    }

    static FastScanner in;
    static PrintWriter out;

    static class FastScanner {
        BufferedReader in;
        StringTokenizer st;

        public FastScanner(BufferedReader in) {
            this.in = in;
        }

        public String nextToken() {
            while (st == null || !st.hasMoreTokens()) {
                try {
                    st = new StringTokenizer(in.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

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

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

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


import javafx.geometry.Pos;
import javafx.util.Pair;

import java.io.*;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.security.cert.PolicyNode;
import java.util.*;

public class Solution {
    BufferedReader in;
    PrintWriter out;
    StringTokenizer st;

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

    final int inf = Integer.MAX_VALUE / 2;
    final double eps = 0.0000000001;

    int rd() throws IOException {
        return Integer.parseInt(nextToken());
    }
    double rdd() throws IOException {
        return Double.parseDouble(nextToken());
    }
    long rdl() throws IOException {
        return Long.parseLong(nextToken());
    }

    int n;
    int[] a;

    int f(int x, int l){
        if (l <= 1){
            return a[x];
        } else {
            return a[f(x, l - 1)];
        }
    }

    void solve() throws IOException {
        n = rd();
        a = new int[n];
        for (int i = 0; i < n; i++) {
            a[i] = rd() - 1;
        }
        for (int k = 1; k <= n + 2; k++) {
            int cnt = 0;
            for (int i = 0; i < n; i++) {
                if (f(i, 2 * k) == f(i, k)) {
                    cnt++;
                }
            }
            if (cnt == n) {
                out.println(k);
                out.flush();
                System.exit(0);
            }
        }
    }

    void run() throws IOException {
        try {
//            in = new BufferedReader(new FileReader("notation.in"));
//            out = new PrintWriter("notation.out");
            in = new BufferedReader(new InputStreamReader(System.in));
            out = new PrintWriter(System.out);
            Locale.setDefault(Locale.UK);
            solve();
        } catch (Exception e) {
            e.printStackTrace();//To change body of catch statement use File | Settings | File Templates.
        } finally {
            out.close();
        }
    }

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


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

@SuppressWarnings("unchecked")

public class Main implements Runnable {

    public static final String FILENAME = null;

    final int maxn = 210;
    int p[] = new int[maxn];
    int mark[] = new int[maxn];

    private void solve() throws IOException {
        int n = nextInt();
        for (int i = 0; i < n; ++i) p[i] = nextInt() - 1;
        int min = 1;
        BigInteger del = BigInteger.ONE;
        for (int i = 0; i < n; ++i) if (mark[i] == 0)
        {
            int x = i;
            int cnt = 0;
            while (true)
            {
                mark[x] = ++cnt;
                if (mark[p[x]] == 0)
                {
                    x = p[x];
                }
                else if (mark[p[x]] > 0)
                {
                    min = Math.max(min, mark[p[x]] - 1);
                    BigInteger cyc = BigInteger.valueOf(mark[x] - mark[p[x]] + 1);
                    del = del.multiply(cyc).divide(del.gcd(cyc));
                    break;
                }
                else break;
            }
            x = i;
            while (true)
            {
                mark[x] = -1;
                if (mark[p[x]] != -1) x = p[x];
                else break;
            }
        }
        BigInteger res = del;
        while (res.compareTo(BigInteger.valueOf(min)) < 0) res = res.add(del);
        out.println(res);

    }
    // -----------------------------------------------
    private BufferedReader br;
    private StringTokenizer _st;
    private PrintWriter out;

    private void myAssert(boolean assertion) {
        if (!assertion) throw new AssertionError();
    }
    private void dbg(Object...os){
        System.err.println(Arrays.deepToString(os));
        System.err.flush();
    }
    private String next() throws IOException {
        while (_st == null || !_st.hasMoreTokens()) {
            String s = br.readLine();
            if (s == null) return null;
            _st = new StringTokenizer(s);
        }
        return _st.nextToken();
    }
    private int nextInt() throws IOException {
        return Integer.parseInt(next());
    }
    private long nextLong() throws IOException {
        return Long.parseLong(next());
    }
    private double nextDouble() throws IOException {
        return Double.parseDouble(next());
    }
    private String nextLine() throws IOException {
        _st = null;
        return br.readLine();
    }
    public void run() {
        long startTime = System.nanoTime();
        try {
            if (FILENAME == null) {
                br = new BufferedReader(new InputStreamReader(System.in));
                out = new PrintWriter(System.out);
            } else {
                br = new BufferedReader(new FileReader(FILENAME + ".in"));
                out = new PrintWriter(FILENAME + ".out");
            }
            try {
                solve();
            } finally {
                out.close();
            }
        } catch (IOException e) {
            System.err.println(e.getClass().getName() + ": " + e.getMessage());
            e.printStackTrace();
        }
        long finishTime = System.nanoTime();
//      System.err.printf("Time = %.3f\n", (finishTime - startTime) / 1e9);
    }
    public static void main(String[] args) {
        new Thread(new Main()).start();
    }

}


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

@SuppressWarnings("unchecked")

public class Main implements Runnable {

    public static final String FILENAME = null;

    final int maxn = 210;
    int p[] = new int[maxn];
    int mark[] = new int[maxn];

    private void solve() throws IOException {
        int n = nextInt();
        for (int i = 0; i < n; ++i) p[i] = nextInt() - 1;
        int min = 1;
        BigInteger del = BigInteger.ONE;
        for (int i = 0; i < n; ++i) if (mark[i] == 0)
        {
            int x = i;
            int cnt = 0;
            int cc = 0;
            while (true)
            {
                mark[x] = ++cnt;
                if (mark[p[x]] == 0)
                {
                    x = p[x];
                }
                else if (mark[p[x]] > 0)
                {
                    min = Math.max(min, mark[p[x]] - 1);
                    BigInteger cyc = BigInteger.valueOf(mark[x] - mark[p[x]] + 1);
                    del = del.multiply(cyc).divide(del.gcd(cyc));
                    cc = mark[p[x]];
                    break;
                }
                else
                {
                    min = Math.max(min, mark[x] - 1 - mark[p[x]]);
                    break;
                }

            }
            x = i;
            cnt = 0;
            while (true)
            {
                mark[x] = Math.min(-1, (++cnt) - cc - 1);
                if (mark[p[x]] != -1) x = p[x];
                else break;
            }
        }
        BigInteger res = del;
        while (res.compareTo(BigInteger.valueOf(min)) < 0) res = res.add(del);
        out.println(res);

    }
    // -----------------------------------------------
    private BufferedReader br;
    private StringTokenizer _st;
    private PrintWriter out;

    private void myAssert(boolean assertion) {
        if (!assertion) throw new AssertionError();
    }
    private void dbg(Object...os){
        System.err.println(Arrays.deepToString(os));
        System.err.flush();
    }
    private String next() throws IOException {
        while (_st == null || !_st.hasMoreTokens()) {
            String s = br.readLine();
            if (s == null) return null;
            _st = new StringTokenizer(s);
        }
        return _st.nextToken();
    }
    private int nextInt() throws IOException {
        return Integer.parseInt(next());
    }
    private long nextLong() throws IOException {
        return Long.parseLong(next());
    }
    private double nextDouble() throws IOException {
        return Double.parseDouble(next());
    }
    private String nextLine() throws IOException {
        _st = null;
        return br.readLine();
    }
    public void run() {
        long startTime = System.nanoTime();
        try {
            if (FILENAME == null) {
                br = new BufferedReader(new InputStreamReader(System.in));
                out = new PrintWriter(System.out);
            } else {
                br = new BufferedReader(new FileReader(FILENAME + ".in"));
                out = new PrintWriter(FILENAME + ".out");
            }
            try {
                solve();
            } finally {
                out.close();
            }
        } catch (IOException e) {
            System.err.println(e.getClass().getName() + ": " + e.getMessage());
            e.printStackTrace();
        }
        long finishTime = System.nanoTime();
//      System.err.printf("Time = %.3f\n", (finishTime - startTime) / 1e9);
    }
    public static void main(String[] args) {
        new Thread(new Main()).start();
    }

}


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

public class F {
	FastScanner in;
	PrintWriter out;

	void solve() {
		int n = in.nextInt();
		int[] f = new int[n];
		for (int i = 0; i < n; i++) {
			f[i] = in.nextInt() - 1;
		}
		BigInteger res = BigInteger.ONE;
		for (int i = 0; i < n; i++) {
			int[] d = new int[n];
			Arrays.fill(d, -1);
			int cur = i;
			int curd = 0;
			int d0 = -1, d1 = -1;
			while (true) {
				d[cur] = curd;
				curd++;
				cur = f[cur];
				if (d[cur] != -1) {
					d0 = d[cur];
					d1 = curd - d[cur];
					break;
				}
			}
			if (d0 == 0)
				d0 = 1;
			//System.out.println(d0 + " " + d1);
			long x = ((d0 + d1 - 1) / d1) * d1;
			//System.out.println(x);
			BigInteger g = BigInteger.valueOf(x).gcd(res);
			res = res.multiply(BigInteger.valueOf(x)).divide(g);
		}
		out.println(res);
	}

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

		solve();

		out.close();
	}

	class FastScanner {
		BufferedReader br;
		StringTokenizer st;

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

		String next() {
			while (st == null || !st.hasMoreTokens()) {
				try {
					st = new StringTokenizer(in.br.readLine());
				} catch (IOException e) {
					// TODO Auto-generated catch block
					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[] args) {
		new F().run();
	}
}


import java.util.*;
public class Problem0171e {
    public static void main(String[] args) {
        System.out.println("INTERCAL");
    }
}


public class Main
{
    public static void main(String[] args)
	{
        System.out.println("INTERCAL");
    }

}


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

public class Template implements Runnable {

    BufferedReader in;
    PrintWriter out;
    StringTokenizer tok = new StringTokenizer("");

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

    class GraphBuilder {
        int n, m;
        int[] x, y;
        int index;
        int[] size;

        GraphBuilder(int n, int m) {
            this.n = n;
            this.m = m;
            x = new int[m];
            y = new int[m];
            size = new int[n];
        }

        void add(int u, int v) {
            x[index] = u;
            y[index] = v;
            size[u]++;
            size[v]++;
            index++;
        }

        int[][] build() {
            int[][] graph = new int[n][];
            for (int i = 0; i < n; i++) {
                graph[i] = new int[size[i]];
            }
            for (int i = index - 1; i >= 0; i--) {
                int u = x[i];
                int v = y[i];
                graph[u][--size[u]] = v;
                graph[v][--size[v]] = u;
            }
            return graph;
        }
    }

    String readString() throws IOException {
        while (!tok.hasMoreTokens()) {
            try {
                tok = new StringTokenizer(in.readLine());
            } catch (Exception e) {
                return null;
            }
        }
        return tok.nextToken();
    }

    int readInt() throws IOException {
        return Integer.parseInt(readString());
    }

    int[] readIntArray(int size) throws IOException {
        int[] res = new int[size];
        for (int i = 0; i < size; i++) {
            res[i] = readInt();
        }
        return res;
    }

    long[] readLongArray(int size) throws IOException {
        long[] res = new long[size];
        for (int i = 0; i < size; i++) {
            res[i] = readLong();
        }
        return res;
    }

    long readLong() throws IOException {
        return Long.parseLong(readString());
    }

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

    <T> List<T>[] createGraphList(int size) {
        List<T>[] list = new List[size];
        for (int i = 0; i < size; i++) {
            list[i] = new ArrayList<>();
        }
        return list;
    }

    public static void main(String[] args) {
        new Template().run();
        // new Thread(null, new Template(), "", 1l * 200 * 1024 * 1024).start();
    }

    long timeBegin, timeEnd;

    void time() {
        timeEnd = System.currentTimeMillis();
        System.err.println("Time = " + (timeEnd - timeBegin));
    }

    long memoryTotal, memoryFree;

    void memory() {
        memoryFree = Runtime.getRuntime().freeMemory();
        System.err.println("Memory = " + ((memoryTotal - memoryFree) >> 10)
                + " KB");
    }

    public void run() {
        try {
            timeBegin = System.currentTimeMillis();
            memoryTotal = Runtime.getRuntime().freeMemory();
            init();
            solve();
            out.close();
            if (System.getProperty("ONLINE_JUDGE") == null) {
                time();
                memory();
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(-1);
        }
    }

    void solve() throws IOException {
        out.println("INTERCAL");
    }

}


import java.util.*;
public class Problem0171e {
    public static void main(String[] args) {
        System.out.println("COBOL");
    }
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Locale;
import java.util.Stack;
import java.util.StringTokenizer;

public class E {

	private void solve() throws IOException {
		int nf = nextInt();
		int ne = nextInt();
		int ns = nextInt();
		int rf = nextInt();
		int re = nextInt();
		int rs = nextInt();
		int df = nextInt();
		int de = nextInt();

		int n = nf + ne + ns;
		byte[] a = new byte[n];
		for (int i = 0; i < ns; i++) {
			a[i] = 1;
		}

		int sqrs = rs * rs;

		int cases = 0;

		int t = 2 * ns + 2;
		double[] p = new double[t];
		int[] b = new int[n];
		double[] f = new double[n];
		double[] e = new double[n];
		double[][] dp = new double[nf + 1][ne + 1];

		double res = 0;

		double d = Math.sqrt(sqrs - 1);
		while (true) {
			cases++;
			int k = 0;
			int q = 0;
			for (int i = 0; i < n; i++) {
				int x = 1000000 + i / 2;
				if (a[i] == 1) {
					p[k++] = x - d;
					p[k++] = -(x + d);
				} else {
					b[q++] = x;
				}
			}
			p[k++] = 0.0;
			p[k++] = -2000000.0;
//			Arrays.sort(p, cmp);
			for (int i = 0; i < p.length; i++) {
				for (int j = i + 1; j < p.length; j++) {
					if (Math.abs(p[i]) > Math.abs(p[j])) {
						double tmp = p[i];
						p[i] = p[j];
						p[j] = tmp;
					}
				}
			}

			for (int i = 0; i < q; i++) {
				f[i] = f(p, b[i], df, rf);
				e[i] = f(p, b[i], de, re);
			}

			for (int i = 1; i <= nf; i++) {
				dp[i][0] = dp[i - 1][0] + f[i - 1];
			}
			for (int i = 1; i <= ne; i++) {
				dp[0][i] = dp[0][i - 1] + e[i - 1];
			}

			for (int i = 1; i <= nf; i++) {
				for (int j = 1; j <= ne; j++) {
					dp[i][j] = Math.max(dp[i - 1][j] + f[i + j - 1], dp[i][j - 1] + e[i + j - 1]);
				}
			}

			res = Math.max(res, dp[nf][ne]);

			boolean next = false;
			int ones = 0;
			for (int i = 0; i < a.length; i++) {
				if (a[i] == 0) {
					if (ones != 0) {
						a[i] = 1;
						for (int j = 0; j < ones - 1; j++) {
							a[j] = 1;
						}
						for (int j = ones - 1; j < i; j++) {
							a[j] = 0;
						}
						next = true;
						break;
					}
				} else {
					ones++;
				}
			}

			if (!next) {
				break;
			}
		}

		println(res);
	}

	private double f(double[] p, int x, double damage, double R) {
		double dx = Math.sqrt(R * R - 1);
		double l = x - dx;
		double r = x + dx;

		double k = 1;
		double res = 0;
		for (int i = 1; i < p.length; i++) {
			double inter = inter(p[i - 1], p[i], l, r);
			res += damage * inter * k;
			if (p[i] > 0) {
				k++;
			} else {
				k--;
			}
		}

		return res;
	}

	private double inter(double l1, double r1, double l2, double r2) {
		l1 = Math.abs(l1);
		r1 = Math.abs(r1);
		l2 = Math.abs(l2);
		r2 = Math.abs(r2);
		double r = Math.min(r1, r2) - Math.max(l1, l2);
		if (r < 0) {
			return 0;
		} else {
			return r;
		}
	}

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

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

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

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

	private void print(Object o) {
		writer.print(o);
	}

	private void println(Object o) {
		writer.println(o);
	}

	private void printf(String format, Object... o) {
		writer.printf(format, o);
	}

	public static void main(String[] args) {
		long time = System.currentTimeMillis();
		Locale.setDefault(Locale.US);
		new E().run();
		System.err.printf("%.3f\n", 1e-3 * (System.currentTimeMillis() - time));
	}

	BufferedReader reader;
	StringTokenizer tokenizer;
	PrintWriter writer;

	private void run() {
		try {
			reader = new BufferedReader(new InputStreamReader(System.in));
			writer = new PrintWriter(System.out);
			solve();
			reader.close();
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
			System.exit(13);
		}
	}
}


//package round115;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;

public class E {
	InputStream is;
	PrintWriter out;
	String INPUT = "";
	int nf, ne, ns, rf, re, rs, df, de;
	int[] fct;

	void solve()
	{
		nf = ni(); ne = ni(); ns = ni();
		rf = ni(); re = ni(); rs = ni();
		df = ni(); de = ni();
		fct = new int[13];

		sqs = Math.sqrt(rs*rs-1);
		sqf = Math.sqrt(rf*rf-1);
		sqe = Math.sqrt(re*re-1);

		rec(0, 0);
		out.printf("%.9f\n", gm);
	}

	double gm = 0;
	double sqs, sqf, sqe;

	void rec(int pos, int num)
	{
		if(pos == 13){
			if(num == ns)go();
		}else{
			for(int i = 0;i <= 2 && num+i <= ns;i++){
				fct[pos] = i;
				rec(pos+1, num+i);
			}
		}
	}

	boolean[] cache = new boolean[3*3*3*3*3*3*3*3*3*3*3*3*3];
	int gct = 0;

	void go()
	{
		int code =  0;
		for(int i = 0;i < 13;i++){
			code = code * 3 + fct[i];
		}
		if(cache[code])return;
		code = 0;
		for(int i = 12;i >= 0;i--){
			code = code * 3 + fct[i];
		}
		cache[code] = true;

		double I = -999999999;
		double[][] dp = new double[nf+1][ne+1];
		for(int j = 0;j <= nf;j++)Arrays.fill(dp[j], I);
		dp[0][0] = 0;

		for(int i = 0;i < 13;i++){
			double tdf = calc(i-sqf, i+sqf) * df;
			double tde = calc(i-sqe, i+sqe) * de;
			for(int j = nf;j >= 0;j--){
				for(int k = ne;k >= 0;k--){
					if(dp[j][k] != I){
						for(int l = 0;l <= 2-fct[i] && j+l <= nf;l++){
							for(int m = 0;l+m <= 2-fct[i] && k+m <= ne;m++){
								dp[j+l][k+m] = Math.max(dp[j+l][k+m], dp[j][k] + tdf*l + tde*m);
							}
						}
					}
				}
			}
		}
//		for(int i = 1;i <= 13;i++){
//			double tdf = calc(ev, i-1-sqf, i-1+sqf) * df;
//			double tde = calc(ev, i-1-sqe, i-1+sqe) * de;
//			for(int j = 0;j <= nf;j++){
//				for(int k = 0;k <= ne;k++){
//					double max = 0;
//					for(int l = 0;l <= 2-fct[i-1] && l <= j;l++){
//						for(int m = 0;l+m <= 2-fct[i-1] && m <= k;m++){
//							max = Math.max(max, dp[i-1][j-l][k-m] + tdf*l + tde*m);
//						}
//					}
//					dp[i][j][k] = max;
//				}
//			}
//		}
		gm = Math.max(gm, dp[nf][ne]);
	}

	double calc(double s, double t)
	{
		double dmg = 0;
		for(int i = 0;i < 13;i++){
			if(fct[i] > 0){
				double w = Math.min(t, i+sqs) - Math.max(s, i-sqs);
				if(w > 0)dmg += w * fct[i];
			}
		}
		return dmg + (t-s);
	}

	void run() throws Exception
	{
		is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
		out = new PrintWriter(System.out);

		long s = System.currentTimeMillis();
		solve();
		out.flush();
		tr(System.currentTimeMillis()-s+"ms");
	}

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

	public int ni()
	{
		try {
			int num = 0;
			boolean minus = false;
			while((num = is.read()) != -1 && !((num >= '0' && num <= '9') || num == '-'));
			if(num == '-'){
				num = 0;
				minus = true;
			}else{
				num -= '0';
			}

			while(true){
				int b = is.read();
				if(b >= '0' && b <= '9'){
					num = num * 10 + (b - '0');
				}else{
					return minus ? -num : num;
				}
			}
		} catch (IOException e) {
		}
		return -1;
	}

	public long nl()
	{
		try {
			long num = 0;
			boolean minus = false;
			while((num = is.read()) != -1 && !((num >= '0' && num <= '9') || num == '-'));
			if(num == '-'){
				num = 0;
				minus = true;
			}else{
				num -= '0';
			}

			while(true){
				int b = is.read();
				if(b >= '0' && b <= '9'){
					num = num * 10 + (b - '0');
				}else{
					return minus ? -num : num;
				}
			}
		} catch (IOException e) {
		}
		return -1;
	}

	public String ns()
	{
		try{
			int b = 0;
			StringBuilder sb = new StringBuilder();
			while((b = is.read()) != -1 && (b == '\r' || b == '\n' || b == ' '));
			if(b == -1)return "";
			sb.append((char)b);
			while(true){
				b = is.read();
				if(b == -1)return sb.toString();
				if(b == '\r' || b == '\n' || b == ' ')return sb.toString();
				sb.append((char)b);
			}
		} catch (IOException e) {
		}
		return "";
	}

	public char[] ns(int n)
	{
		char[] buf = new char[n];
		try{
			int b = 0, p = 0;
			while((b = is.read()) != -1 && (b == ' ' || b == '\r' || b == '\n'));
			if(b == -1)return null;
			buf[p++] = (char)b;
			while(p < n){
				b = is.read();
				if(b == -1 || b == ' ' || b == '\r' || b == '\n')break;
				buf[p++] = (char)b;
			}
			return Arrays.copyOf(buf, p);
		} catch (IOException e) {
		}
		return null;
	}

	double nd() { return Double.parseDouble(ns()); }
	boolean oj = System.getProperty("ONLINE_JUDGE") != null;
	void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}


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

public class E
{
    public static void main(String [] args) throws IOException
    {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter writer = new PrintWriter(System.out);

        StringTokenizer tokenizer = new StringTokenizer(reader.readLine());
        int nf = Integer.parseInt(tokenizer.nextToken());
        int ne = Integer.parseInt(tokenizer.nextToken());
        int ns = Integer.parseInt(tokenizer.nextToken());
        int total = nf + ne + ns;

        tokenizer = new StringTokenizer(reader.readLine());
        double rf = Integer.parseInt(tokenizer.nextToken());
        double re = Integer.parseInt(tokenizer.nextToken());
        double rs = Integer.parseInt(tokenizer.nextToken());
        rf *= rf;
        rf -= 1;
        rf = Math.sqrt(rf);

        re *= re;
        re -= 1;
        re = Math.sqrt(re);

        rs *= rs;
        rs -= 1;
        rs = Math.sqrt(rs);

        tokenizer = new StringTokenizer(reader.readLine());
        int df = Integer.parseInt(tokenizer.nextToken());
        int de = Integer.parseInt(tokenizer.nextToken());

        double res = 0;

        for(int s = 0 ; s < 1<<total ; s++)
            if(Integer.bitCount(s) == ns)
            {
                double [] a = new double[ns];
                double [] b = new double[ns];
                int p = 0;
                for(int i = 0 ; i < total ; i++)
                    if(((1<<i) & s) != 0)
                    {
                        a[p] = i/2 - rs;
                        b[p] = i/2 + rs;
                        p++;
                    }

                double [] pf = new double[total-ns];
                double [] pe = new double[total-ns];
                int l = 0;
                double left, right;
                for(int i = 0 ; i < total ; i++)
                    if(((1<<i) & s) == 0)
                    {
                        pf[l] = 2*rf*df;
                        pe[l] = 2*re*de;

                        for(int j = 0 ; j < p ; j++)
                        {
                            {
                                left = i/2 - rf;
                                right = i/2 + rf;
                                left = Math.max(left, a[j]);
                                right = Math.min(right, b[j]);
                                if(left <= right)
                                {
                                    pf[l] += (right-left)*df;
                                }
                            }
                            {
                                left = i/2 - re;
                                right = i/2 + re;
                                left = Math.max(left, a[j]);
                                right = Math.min(right, b[j]);
                                if(left <= right)
                                {
                                    pe[l] += (right-left)*de;
                                }
                            }

                        }
                        l++;
                    }

                double [][] dp = new double[l+1][nf+1];
                boolean [][] reach = new boolean[l+1][nf+1];
                reach[0][0] = true;
                for(int till = 0 ; till < l ; till++)
                    for(int v = 0 ; v <= nf ; v++)
                        if(reach[till][v])
                        {
                            if(v != nf)
                            {
                                dp[till+1][v+1] = Math.max(dp[till+1][v+1], dp[till][v] + pf[till]);
                                reach[till+1][v+1] = true;
                            }
                            if(till-v != ne)
                            {
                                dp[till+1][v] = Math.max(dp[till+1][v], dp[till][v] +pe[till]);
                                reach[till+1][v] = true;
                            }
                        }

                res = Math.max(res, dp[l][nf]);
            }

        writer.println(res);
        writer.flush();
        writer.close();

    }
}


package croc.Final;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;

public class E {
	InputStream is;
	PrintWriter out;
	String INPUT = "";

	void solve()
	{
		int n = ni();
		long x = 1, y = 1;
		for(int i = 0;i < n;i++){
			char[] s = ns(4);
			if(s.length == 4){
				x++; y++;
			}else if(s[0] == 'U' && s[1] == 'L'){
				x++;
			}else if(s[0] == 'D' && s[1] == 'R'){
				x++;
			}else{
				y++;
			}
		}
		out.println(x*y);
	}

	void run() throws Exception
	{
		is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
		out = new PrintWriter(System.out);

		long s = System.currentTimeMillis();
		solve();
		out.flush();
		tr(System.currentTimeMillis()-s+"ms");
	}

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

	public int ni()
	{
		try {
			int num = 0;
			boolean minus = false;
			while((num = is.read()) != -1 && !((num >= '0' && num <= '9') || num == '-'));
			if(num == '-'){
				num = 0;
				minus = true;
			}else{
				num -= '0';
			}

			while(true){
				int b = is.read();
				if(b >= '0' && b <= '9'){
					num = num * 10 + (b - '0');
				}else{
					return minus ? -num : num;
				}
			}
		} catch (IOException e) {
		}
		return -1;
	}

	public long nl()
	{
		try {
			long num = 0;
			boolean minus = false;
			while((num = is.read()) != -1 && !((num >= '0' && num <= '9') || num == '-'));
			if(num == '-'){
				num = 0;
				minus = true;
			}else{
				num -= '0';
			}

			while(true){
				int b = is.read();
				if(b >= '0' && b <= '9'){
					num = num * 10 + (b - '0');
				}else{
					return minus ? -num : num;
				}
			}
		} catch (IOException e) {
		}
		return -1;
	}

	public String ns()
	{
		try{
			int b = 0;
			StringBuilder sb = new StringBuilder();
			while((b = is.read()) != -1 && (b == '\r' || b == '\n' || b == ' '));
			if(b == -1)return "";
			sb.append((char)b);
			while(true){
				b = is.read();
				if(b == -1)return sb.toString();
				if(b == '\r' || b == '\n' || b == ' ')return sb.toString();
				sb.append((char)b);
			}
		} catch (IOException e) {
		}
		return "";
	}

	public char[] ns(int n)
	{
		char[] buf = new char[n];
		try{
			int b = 0, p = 0;
			while((b = is.read()) != -1 && (b == ' ' || b == '\r' || b == '\n'));
			if(b == -1)return null;
			buf[p++] = (char)b;
			while(p < n){
				b = is.read();
				if(b == -1 || b == ' ' || b == '\r' || b == '\n')break;
				buf[p++] = (char)b;
			}
			return Arrays.copyOf(buf, p);
		} catch (IOException e) {
		}
		return null;
	}

	double nd() { return Double.parseDouble(ns()); }
	boolean oj = System.getProperty("ONLINE_JUDGE") != null;
	void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}


import java.util.List;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.math.BigInteger;
import java.util.Collections;
import java.io.InputStream;

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

class TaskE {
        final int MAX_N = 101_000;
        @SuppressWarnings("uncheked")
        ArrayList<Integer>[] divs = new ArrayList[MAX_N];
        long modulo;

        public void solve(int testNumber, FastScanner in, PrintWriter out) {
                init();
                int n = in.nextInt();
                int m = in.nextInt();
                long L = in.nextInt();
                long R = in.nextInt();
                modulo = in.nextInt();
                long res = 0;
                for (long dx = 1; dx <= n; dx++) {
                        long low = L * L - dx * dx;
                        long high = R * R - dx * dx;
                        if (low < 0)
                                low = 0;
                        if (high < 0)
                                continue;
                        long left = (int)Math.sqrt(low);
                        long right = (int)Math.sqrt(high);
                        while (left > 0 && left * left + dx * dx > L * L)
                                left--;
                        while (left * left + dx * dx <= L * L)
                                left++;
                        left--;
                        while (right * right + dx * dx <= R * R)
                                right++;
                        right--;
                        //left--;
                        if (right <= 0)
                                continue;
                        if (left > m)
                                continue;
                        if (left < 0)
                                left = 0;
                        if (right > m)
                                right = m;
                        if (left > right)
                                continue;
                        //out.println(dx + " " + left + " " + right);
                        long cntR = right - getCount((int)dx, (int)right);
                        long cntL = left - getCount((int)dx, (int)left);
                        long cnt = cntR - cntL;
                        cnt %= modulo;
                        cnt += modulo;
                        cnt %= modulo;;
                        //out.println("cnt = " + cnt);
                        long sumR = right * (right + 1) / 2 - getSum((int)dx, (int)right);
                        long sumL = left * (left + 1) / 2 - getSum((int)dx, (int)left);
                        //out.println(sumL);
                        //out.println(sumR);
                        long sum = sumR - sumL;
                        //out.println("sum = " + sum);
                        sum = cnt * (m + 1) % modulo - sum;
                        sum %= modulo;
                        sum += modulo;
                        sum %= modulo;
                        res += (2 * sum * (n - dx + 1)) % modulo;
                        res %= modulo;
                }
                if (L <= 1)
                        res += (n + 1) * 1L * m + n * 1L * (m + 1);
                out.println(res % modulo);
        }

        void init() {
                for (int i = 1; i < MAX_N; i++) {
                        divs[i] = new ArrayList<>();
                        divs[i].add(1);
                }
                for (int i = 2; i < MAX_N; i++)
                        for (int j = i; j < MAX_N; j += i)
                                divs[j].add(i);
                for (int i = 1; i < MAX_N; i++)
                        Collections.reverse(divs[i]);
        }

        long getCount(int n, int R) {
                if (n == 1)
                        return 0L;
                if (R <= 1)
                        return 0L;
                int cnt = divs[n].size();
                int[] with = new int[cnt];
                int res = 0;
                for (int i = 0; i < cnt - 1; i++) {
                        int cur = divs[n].get(i);
                        with[i] += R / cur;
                        res += with[i];
                        for (int j = cnt - 1; j >= 0 && divs[n].get(j) < cur; j--)
                                if (cur % divs[n].get(j) == 0)
                                        with[j] -= with[i];
                }
                return res;
        }

        long getSum(int n, int R) {
                if (R <= 1)
                        return 0L;
                if (n == 1)
                        return 0L;
                int cnt = divs[n].size();
                long[] with = new long[cnt];
                long res = 0;
                for (int i = 0; i < cnt - 1; i++) {
                        int cur = divs[n].get(i);
                        with[i] += (R / cur * 1L * (R / cur + 1) / 2) % modulo * cur;
                        with[i] %= modulo;
                        res += with[i];
                        res %= modulo;
                        for (int j = cnt - 1; j >= 0 && divs[n].get(j) < cur; j--)
                                if (cur % divs[n].get(j) == 0) {
                                        with[j] -= with[i];
                                        with[j] %= modulo;
                                        if (with[j] < 0)
                                                with[j] += modulo;
                                }
                }
                return res;
        }

        }

class FastScanner {
        BufferedReader reader;
        StringTokenizer tokenizer;

        public FastScanner(InputStream inputStream)  {
                reader = new BufferedReader(new InputStreamReader(inputStream));
        }

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

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

        }