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

public class A {
	public static void main(String[] args) throws IOException {
		st = new StringTokenizer(rd.readLine());
		M = Integer.parseInt(st.nextToken());
		N = Integer.parseInt(st.nextToken());
		F[0] = 1;
	//	for(int i=0; i<=4000; i++) for(int j=0; j<=4000; j++) g[i][j] = gcd(i, j);
		for(int i=1; i<F.length; i++) F[i] = (F[i-1]*i)%Q;
		for(int i=0; i<IF.length; i++) IF[i] = pow(F[i], Q-2);
		long[] X = new long[4];
		long numEven1 = N/2+1, numOdd1 = N+1-numEven1, numEven2 = M/2+1, numOdd2 = M+1-numEven2;
		X[0] = numEven1*numEven2;
		X[1] = numEven1*numOdd2;
		X[2] = numOdd1*numEven2;
		X[3] = numOdd1*numOdd2;
	//	System.out.println(Arrays.toString(X));
		P = new Point[4];
		P[0] = new Point(0, 0);
		P[1] = new Point(0, 1);
		P[2] = new Point(1, 0);
		P[3] = new Point(1, 1);
		long res = 0;
		for(int i=0; i<4; i++){
			for(int j=0; j<4; j++){
				for(int k=0; k<4; k++){
					if(isOk(i, j, k)){
						if(i!=j && j!=k && i!=k){
							res = (res + X[i]*X[j]*X[k])%Q;
						}
						else if(i!=j && j!=k && i==k){
							res = (res + (X[i]>0? X[i]*X[j]*(X[i]-1): 0))%Q;
						}
						else if(i!=j && j==k && i!=k){
							res = (res + (X[j]>0? X[i]*(X[j])*(X[j]-1): 0))%Q;
						}
						else if(i!=j && j==k && i==k){
							//
						}
						else if(i==j && j!=k && i!=k){
							res = (res + (X[i]>0? X[i]*(X[i]-1)*X[k]: 0))%Q;
						}
						else if(i==j && j!=k && i==k){
							//
						}
						else if(i==j && j==k && i!=k){
							//
						}
						else if(i==j && j==k && i==k){
							res = (res + (X[i]>1? X[i]*(X[i]-1)*(X[i]-2): 0))%Q;
						}
					}
				}
			}
		}
		pw.println((res-numOnLine()+Q)%Q);
		int r = 0;
		pw.flush();
		if(r==0) return;
		for(int x1=0; x1<=M; x1++){
			for(int x2=0; x2<=M; x2++){
				for(int x3=0; x3<=M; x3++){
					for(int y1=0; y1<=N; y1++){
						for(int y2=0; y2<=N; y2++){
							for(int y3=0; y3<=N; y3++){
								int s = Math.abs(x1*(y2-y3)+x2*(y3-y1)+x3*(y1-y2));
								if(s!=0 && s%2==0) r++;
							}
						}
					}
				}
			}
		}
//		System.out.println(r);
	}

	static int numOnLine(){
		long res = 0;
		for(int m=0; m<=M; m++){
			for(int n=0; n<=N; n++){
				long mult = (M-m+1)*(N-n+1);
				if(m==0 || n==0){
					int s = m+n;
					if(s>=2){
						res = (res + mult*(s-1)*6)%Q;
		//				System.out.println("XAZI");
					}
				}
				else{
					int d = gcd(m, n);
					int t = n/d;
					int num = n/t+1;
					if(num>=3){
				//		if(m<2 && n<2) System.out.println("TY");
		//				System.out.println("diagonali");
						res = (res + mult*(num-2)*12)%Q;
					}
				}
			}
		}
		return (int) res;
	}

	static int gcd1(int x, int y){
		if(x==0 || y==0) return x+y;
		if(x==1 || y==1) return 1;
		if(x>y) return gcd1(x%y, y);
		return gcd1(x, y%x);
	}

	static long getA(int x, int y){
		return F[x]*IF[x-y];
	}

	static long[] F = new long[4001], IF = new long[4001];

	static long pow(long x, long y){
		if(y==0) return 1;
		if(y==1) return x%Q;
		long sq = pow(x, y>>1);
		return y%2==0? (sq*sq)%Q: (((sq*sq)%Q)*x)%Q;
	}

	static int gcd(int x, int y){
		if(x>y) return gcd(y, x);
		if(x==0 || y==0) return x+y;
		if(x==1 || y==1) return 1;
		if((x&1)==0 && (y&1)==0) return 2*gcd(x>>1, y>>1);
		if((x&1)==0) return gcd(x>>1, y);
		if((y&1)==0) return gcd(x, y>>1);
		return gcd(x, (y-x)>>1);
	}

	static int[][] g = new int[4001][4001];

	static int Q = 1000000007;

	static Point[] P;

	static boolean isOk(int i, int j, int k){
		Point a = new Point(P[i].x, P[i].y), b = new Point(P[j].x, P[j].y), c = new Point(P[k].x, P[k].y);
		int mult = a.x*(b.y-c.y)+b.x*(c.y-a.y)+c.x*(a.y-b.y)+1000;
		return mult%2==0;
	}

	static int M, N;

	static BufferedReader rd = new BufferedReader(new InputStreamReader(System.in));
	static PrintWriter pw = new PrintWriter(System.out);
	static StringTokenizer st;

}

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

	public int x, y;

}


java.util.Scanner;

/**
 *
 * @author Mohamed Khafaga
 */
public class TheNewYear {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int[] points = new int[3];
        //double avg = 0;
        int avg = 0;
        int distance = 0;
        for (int i = 0; i < 3; i++) {
            points[i] = in.nextInt();
            avg += points[i];

        }
        if (points[0] == points[1] && points[1] == points[2]) {
            System.out.println(0);
        } else if (points[0] == points[1] || points[1] == points[2] || points[2] == points[0]) {
            System.out.println(Math.max(Math.max(points[0], points[1]), points[2]) -Math.min(Math.min(points[0], points[1]), points[2]));
        } else {
            avg /= 3.0;
            //avg = ((avg-(int)avg)>0.5)? (int)avg+1: (int)avg;
            //avg =  Math.ceil(avg);
            for (int i = 0; i < 3; i++) {
                distance += Math.abs(avg - points[i]);
            }
            System.out.println(distance);
        }

    }
}


public class R266A {
    public static void main (String[] args){
        Scanner t=new Scanner(System.in);
        int n=t.nextInt();
        int m=t.nextInt();
        int a=t.nextInt();
        int b=t.nextInt();
        if ((double)m/b<a){
            System.out.println(n/m*b+n%m*a);

        } else System.out.println(n*a);

    }


/*
 * DA-IICT
 * Author: Jugal Kalal
 */
import java.util.*;
import java.io.*;
import java.math.*;
import java.text.DecimalFormat;
public class HackerEarth{
	static long MOD=(long)Math.pow(10,9)+7;
	public static void main(String args[]) {
        new Thread(null, new Runnable() {
            public void run() {
                try{
                    solve();
                    w.close();
                }
                catch(Exception e){
                    e.printStackTrace();
                }
            }
        }, "1", 1 << 26).start();
	}
	static InputReader in;
    static PrintWriter w;
    static void solve(){
        in = new InputReader(System.in);
        w = new PrintWriter(System.out);
        int x1=in.nextInt();
        int y1=in.nextInt();
        int x2=in.nextInt();
        int y2=in.nextInt();
        int a=in.nextInt();
        int b=in.nextInt();
        double num1=((double)(x2-x1))/(double)a;
        double num2=((double)(y2-y1))/(double)b;
        long ln1=(long)num1;
        long ln2=(long)num2;
        if(((double)ln1==num1&&(double)ln2==num2&&ln1==ln2)||(ln1==0||ln2==0)){
        	w.println("YES");
        }else{
        	w.println("NO");
        }
    }
    static boolean adj[][];
//    static ArrayList<Integer> adj[]; //Adjacency Lists
    static int V;   // No. of vertices
    // Constructor
    static void Graph(int v){
        V = v;
        adj=new boolean[v][v];
//        adj = new ArrayList[v];
//        for (int i=0; i<v; ++i){
//        	adj[i] = new ArrayList();
//        }
    }
    // Function to add an edge into the graph
    static void addEdge(int u,int v){
//		adj[u].add(v);
//		adj[v].add(u);
    	adj[u][v]=true;
    	adj[v][u]=true;
    }
    static int[] isHamiltonian_path(int n){
    	int ans[]=new int[n];
    	int dp[][]=new int[n][1<<n];
    	for(int i=0;i<n;i++){
    		dp[i][1<<i]=0;
    	}
    	for(int mask=0;mask<(1<<n);mask++){
    		for(int j=0;j<n;j++){
    			if((mask&(1<<j))>0){
    				for(int k=0;k<n;k++){
    					if(j!=k&&(mask&(1<<k))>0&&adj[j][k]){
    						dp[j][mask]=Math.max(1+dp[k][mask^(1<<j)],dp[j][mask]);
    					}
    				}
    			}
    		}
    	}
    	for(int i=0;i<n;i++){
    		ans[i]=dp[i][(1<<n)-1];
    	}
    	return ans;
    }
//    static void bfs(int s,int n){
//    	boolean visited[]=new boolean[n];
//    	LinkedList<Integer> queue=new LinkedList<Integer>();
//    	queue.add(s);
//    	visited[s]=true;
//    	while(!queue.isEmpty()){
//    		int num=queue.pop();
////    		System.out.println(ans.toString());
//    		for(int i=0;i<adj[num].size();i++){
//    			if(!visited[adj[num].get(i)]){
//    				visited[adj[num].get(i)]=true;
//    				queue.add(adj[num].get(i));
//    			}
//    		}
//    	}
//    }
    static long gcd(long a,long b){
		if(a==0){
			return b;
		}
		return gcd(b%a,a);
	}
    static long power(long base, long exponent, long modulus){
	    long result = 1L;
	    while (exponent > 0) {
	        if (exponent % 2L == 1L)
	            result = (result * base) % modulus;
	        exponent = exponent >> 1;
	        base = (base * base) % modulus;
	    }
	    return result;
	}
    static HashMap<Long,Long> primeFactors(long n){
        HashMap<Long,Long> ans=new HashMap<Long,Long>();
    	// Print the number of 2s that divide n
        while (n%2L==0L)
        {
            if(ans.containsKey(2L)){
            	ans.put(2L,ans.get(2L)+1L);
            }else{
            	ans.put(2L,1L);
            }
            n /= 2L;
        }

        // n must be odd at this point.  So we can
        // skip one element (Note i = i +2)
        for (long i = 3; i <= Math.sqrt(n); i+= 2L)
        {
            // While i divides n, print i and divide n
            while (n%i == 0)
            {
            	if(ans.containsKey(i)){
                	ans.put(i,ans.get(i)+1L);
                }else{
                	ans.put(i,1L);
                }
                n /= i;
            }
        }

        // This condition is to handle the case whien
        // n is a prime number greater than 2
        if (n > 2)
            ans.put(n,1L);
        return ans;
    }
////for marking all prime numbers greater than 1 and less than equal to N
	static void sieve(int N) {
	 boolean isPrime[]=new boolean[N+1];
	 isPrime[0] = true;
	 isPrime[1] = true;
	 for(int i = 2; i * i <= N; ++i) {
	      if(isPrime[i] == false) {//Mark all the multiples of i as composite numbers
	          for(int j = i * i; j <= N ;j += i)
	              isPrime[j] = true;
	     }
	 }
	}
//  //if  str2 (pattern) is subsequence of str1 (Text) or not
//	static boolean function(String str1,String str2){
//	     str2 = str2.replace("", ".*");  //returns .*a.*n.*n.*a.
//	     return (str1.matches(str2));  // returns true
//	}
    static int Arr[];
    static long size[];
  //modified initialize function:
    static void initialize(int N){
    	Arr=new int[N];
    	size=new long[N];
        for(int i = 0;i<N;i++){
        	Arr[ i ] = i ;
        	size[ i ] = 1;
        }
    }
    static boolean find(int A,int B){
        if( root(A)==root(B) )       //if A and B have same root,means they are connected.
        return true;
        else
        return false;
    }
 // modified root function.
    static void weighted_union(int A,int B,int n){
        int root_A = root(A);
        int root_B = root(B);
        if(size[root_A] < size[root_B ]){
        	Arr[ root_A ] = Arr[root_B];
        	size[root_B] += size[root_A];
        }
        else{
        	Arr[ root_B ] = Arr[root_A];
        	size[root_A] += size[root_B];
        }
    }
    static int root (int i){
        while(Arr[ i ] != i){
            Arr[ i ] = Arr[ Arr[ i ] ] ;
            i = Arr[ i ];
        }
        return i;
    }

	static boolean isPrime(long n) {
		if(n < 2L) return false;
		if(n == 2L || n == 3L) return true;
		if(n%2L == 0 || n%3L == 0) return false;
		long sqrtN = (long)Math.sqrt(n)+1L;
		for(long i = 6L; i <= sqrtN; i += 6L) {
			if(n%(i-1) == 0 || n%(i+1) == 0) return false;
		}
		return true;
	}
//	static HashMap<Integer,Integer> level;;
//	static HashMap<Integer,Integer> parent;
	static int maxlevel=0;

//	static boolean T[][][];
//	static void subsetSum(int input[], int total, int count) {
//        T = new boolean[input.length + 1][total + 1][count+1];
//        for (int i = 0; i <= input.length; i++) {
//        	T[i][0][0] = true;
//        	for(int j = 1; j<=count; j++){
//        		T[i][0][j] = false;
//        	}
//        }
//        int sum[]=new int[input.length+1];
//        for(int i=1;i<=input.length;i++){
//            sum[i]=sum[i-1]+input[i-1];
//        }
//        for (int i = 1; i <= input.length; i++) {
//            for (int j = 1; j <= (int)Math.min(total,sum[i]); j++) {
//            	for (int k = 1; k <= (int)Math.min(i,count); k++){
//            		 if (j >= input[i - 1]) {//Exclude and Include
//                         T[i][j][k] = T[i - 1][j][k] || T[i - 1][j - input[i - 1]][k-1];
//                     } else {
//                         T[i][j][k] = T[i-1][j][k];
//                     }
//            	}
//            }
//        }
//    }
//	static <K,V extends Comparable<? super V>>
//	SortedSet<Map.Entry<K,V>> entriesSortedByValues(Map<K,V> map) {
//	    SortedSet<Map.Entry<K,V>> sortedEntries = new TreeSet<Map.Entry<K,V>>(
//	        new Comparator<Map.Entry<K,V>>() {
//	            @Override public int compare(Map.Entry<K,V> e1, Map.Entry<K,V> e2) {
//	                int res = e2.getValue().compareTo(e1.getValue());
//	                return res != 0 ? res : 1;
//	            }
//	        }
//	    );
//	    sortedEntries.addAll(map.entrySet());
//	    return sortedEntries;
//	}

	//minimum prime factor of all the numbers less than n
    static int minPrime[];
	static void minimumPrime(int n){
		minPrime=new int[n+1];
		minPrime[1]=1;
        for (int i = 2; i * i <= n; ++i) {
            if (minPrime[i] == 0) {         //If i is prime
                for (int j = i * i; j <= n; j += i) {
                    if (minPrime[j] == 0) {
                        minPrime[j] = i;
                    }
                }
            }
        }
        for (int i = 2; i <= n; ++i) {
            if (minPrime[i] == 0) {
                minPrime[i] = i;
            }
        }
	}
	static long modInverse(long A, long M)
	{
		long x=extendedEuclid(A,M)[0];
		return (x%M+M)%M;    //x may be negative
	}
	static long[] extendedEuclid(long A, long B) {
		if(B == 0) {
			long d = A;
			long x = 1;
			long y = 0;
			return new long[]{x,y,d};
		}
		else {
			long arr[]=extendedEuclid(B, A%B);
			long temp = arr[0];
			arr[0] = arr[1];
			arr[1] = temp - (A/B)*arr[1];
			return arr;
		}
	}

	static class InputReader {
        private final InputStream stream;
        private final byte[] buf = new byte[8192];
        private int curChar, 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 String nextLine() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            StringBuilder res = new StringBuilder();
            do {
                res.appendCodePoint(c);
                c = read();
            } while (!isEndOfLine(c));
            return res.toString();
        }

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

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

        public int nextInt() {
            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 int[] nextIntArray(int n) {
            int[] arr = new int[n];
            for (int i = 0; i < n; i++) {
                arr[i] = nextInt();
            }
            return arr;
        }

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

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

        private boolean isEndOfLine(int c) {
            return c == '\n' || c == '\r' || c == -1;
        }
        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);
        }
	}
}


import java.util.Scanner;
import java.io.File;
    public class 817A{
	public static void main (String args[]){
		File file1= new File("in.inp");
		File file2= new File("ou.out");
		Scanner inp= new Scanner(System.in);
		int x1=inp.nextInt();
		int y1=inp.nextInt();
		int x2=inp.nextInt();
		int y2=inp.nextInt();
		int a=inp.nextInt();
		int b=inp.nextInt();
		inp.close();
		x1=Math.abs(x2-x1);
		y1=Math.abs(y2-y1);
		if(x1%a!=0) System.out.print("NO");
		else if(y1 % b != 0) System.out.print("NO");
		else if(Math.abs((x1 / a) - (y1 / b)) % 2 != 0) System.out.print("NO");
		else System.out.print("YES");
	}
    }


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package main;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Scanner;
import java.util.Set;

/**
 *
 * @author george150485
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        Scanner sc=new Scanner(System.in);
        String []nn=br.readLine().split(" ");
        int n=Integer.parseInt(nn[0]);
        long ans=0;
        int k;
        //Set<Integer>S=new HashSet<>();
        double p;
        for (int i = n; i >0; --i) {
            for (int j = i-1; j >0; --j) {
              k=(i^j);
                if(k<j&&k>0){
                  //the average of them are > max of them
                 p=((double)(k+i+j)/(double)2);
                 if(p>(Math.max(i, Math.max(j, k))))++ans;
                }

            }
        }
        System.out.println(ans);
    }

}


import java.io.*;
import java.util.*;
public class D {
	private static void solve() throws IOException {
		n = nextInt();
		m = nextInt();
		f = new int[n+1];
		boolean[] visF = new boolean[n+1];
		boolean[] visE = new boolean[n+1];
		Queue<Integer> starts = new LinkedList<Integer>(); //all the locations of starts
		Queue<Integer> ends = new LinkedList<Integer>(); //all the locations of ends
		for(int i = 1; i < n+1; i++) {
			f[i] = nextInt();
			if(f[i] == 1)
				starts.add(i);
			else if(f[i] == 2)
				ends.add(i);
		}
		adj = new ArrayList<LinkedList<Integer>>(m);
		back = new ArrayList<LinkedList<Integer>>(m);
		for(int i = 0; i < n+1; i++) {
			adj.add(new LinkedList<Integer>());
			back.add(new LinkedList<Integer>());
		}
		for(int i = 0; i < m; i++) {
			int f = nextInt();
			int s = nextInt();
			adj.get(f).add(s);
			back.get(s).add(f);
		}
		//see if can be found from a 1
		while(!starts.isEmpty()) {
			int cur = starts.poll();
			if(visF[cur])
				continue;
			visF[cur] = true;
			LinkedList<Integer> temp = adj.get(cur);
			for(int i = 0; i < temp.size(); i++) {
				starts.add(temp.get(i));
			}
		}
		while(!ends.isEmpty()) {
			int cur = ends.poll();
			if(visE[cur])
				continue;
			visE[cur] = true;
			if(f[cur] == 1)
				continue;
			LinkedList<Integer> temp = back.get(cur);
			for(int i = 0; i < temp.size(); i++) {
				ends.add(temp.get(i));
			}
		}
		for(int i = 1; i < visF.length; i++) {
			if(visF[i] && visE[i])
				out.println(1);
			else
				out.println(0);
		}
	}
	static int b, n, m, k, l;
	static int[] a, f;
	static ArrayList<LinkedList<Integer>> adj, back;

	public static void main(String[] args) {
		try {
			br = new BufferedReader(new InputStreamReader(System.in));
			out = new PrintWriter(System.out);
			solve();
			out.close();
		} catch (Throwable e) {
			e.printStackTrace();
			System.exit(239);
		}
	}

	static BufferedReader br;
	static StringTokenizer st;
	static PrintWriter out;

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

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

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

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


import java.io.*;
import java.util.*;
public class D {
	private static void solve() throws IOException {
		n = nextInt();
		m = nextInt();
		f = new int[n+1];
		boolean[] visF = new boolean[n+1];
		boolean[] visE = new boolean[n+1];
		Queue<Integer> starts = new LinkedList<Integer>(); //all the locations of starts
		Queue<Integer> ends = new LinkedList<Integer>(); //all the locations of ends
		for(int i = 1; i < n+1; i++) {
			f[i] = nextInt();
			if(f[i] == 1)
				starts.add(i);
			else if(f[i] == 2)
				ends.add(i);
		}
		adj = new ArrayList[n+1];
		back = new ArrayList[n+1];
		for(int i = 0; i < n+1; i++) {
			adj[i] = new ArrayList<Integer>();
		}
		for(int i = 0; i < m; i++) {
			int f = nextInt();
			int s = nextInt();
			adj[f].add(s);
			back[s].add(f);
		}
		//see if can be found from a 1
		while(!starts.isEmpty()) {
			int cur = starts.poll();
			if(visF[cur])
				continue;
			visF[cur] = true;
			ArrayList<Integer> temp = adj[cur];
			for(int i = 0; i < temp.size(); i++) {
				starts.add(temp.get(i));
			}
		}
		while(!ends.isEmpty()) {
			int cur = ends.poll();
			if(visE[cur])
				continue;
			visE[cur] = true;
			if(f[cur] == 1)
				continue;
			ArrayList<Integer> temp = back[cur];
			for(int i = 0; i < temp.size(); i++) {
				ends.add(temp.get(i));
			}
		}
		for(int i = 1; i < visF.length; i++) {
			if(visF[i] && visE[i])
				out.println(1);
			else
				out.println(0);
		}
	}
	static int b, n, m, k, l;
	static int[] a, f;
	static ArrayList<Integer>[] adj, back;

	public static void main(String[] args) {
		try {
			br = new BufferedReader(new InputStreamReader(System.in));
			out = new PrintWriter(System.out);
			solve();
			out.close();
		} catch (Throwable e) {
			e.printStackTrace();
			System.exit(239);
		}
	}

	static BufferedReader br;
	static StringTokenizer st;
	static PrintWriter out;

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

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

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

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


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.StringTokenizer;

public class D {

    static StringTokenizer st;
    static BufferedReader in;
    static int[]f, p, ans;
    static ArrayList<Integer>[]ages;
    static boolean[]used, assigned;
    public static void main(String[] args) throws IOException {
        in = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
        int n = nextInt();
        int m = nextInt();
        f = new int[n+1];
        for (int i = 1; i <= n; i++) {
            f[i] = nextInt();
        }
        ages = new  ArrayList[n+1];
        for (int i = 1; i <= n; i++) {
            ages[i] = new ArrayList<Integer>();
        }
        for (int i = 1; i <= m; i++) {
            int v1 = nextInt();
            int v2 = nextInt();
            ages[v1].add(v2);
        }
        used = new boolean[n+1];
        p = new int[n+1];
        ans = new int[n+1];
        assigned = new boolean[n+1];
        for (int i = 1; i <= n; i++) {
            if (!used[i] && f[i]==1)
                dfs(i);
        }
        for (int i = 1; i <= n; i++) {
            pw.println(ans[i]);
        }
        pw.close();
    }
    private static void dfs(int v) {
        used[v] = true;
        for (int to : ages[v]) {
            if (to==p[v] || used[to])
                continue;
            p[to] = v;
            if (f[to]==2) {
                int cur = to;
                while (cur != 0 && !assigned[cur]) {
                    assigned[cur] = true;
                    ans[cur] = 1;
                    cur = p[cur];
                }
            }
            dfs(to);
        }
    }
    private static int nextInt() throws IOException{
        return Integer.parseInt(next());
    }

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


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Scanner;
import java.util.Stack;

public class CF_164D {

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

	private void solve() {
		Scanner in = new Scanner(System.in);
		int numNodes = in.nextInt();
		int numEdges = in.nextInt();

		boolean[] rfs = new boolean[numNodes];
		boolean[] rfe = new boolean[numNodes];
		int[] type = new int[numNodes];

		HashMap<Integer, List<Integer>> fwdEdges = new HashMap<Integer, List<Integer>>();
		HashMap<Integer, List<Integer>> revEdges = new HashMap<Integer, List<Integer>>();

		Stack<Integer> startNodes = new Stack<Integer>();
		Stack<Integer> endNodes   = new Stack<Integer>();

		// read nodes
		for(int i = 0; i < numNodes; i++) {
			type[i] = in.nextInt();
			fwdEdges.put(i, new ArrayList<Integer>());
			revEdges.put(i, new ArrayList<Integer>());

			if(type[i] == 1) {
				startNodes.push(i);
			} else if (type[i] == 2) {
				endNodes.push(i);
			}
		}

		// read edges
		for(int i = 0; i < numEdges; i++) {
			int a = in.nextInt() - 1;
			int b = in.nextInt() - 1;
			fwdEdges.get(a).add(b);
			revEdges.get(b).add(a);
		}

		// find all nodes reachable from start nodes without visiting an end node
		// (traverse forward edges)
		while(!startNodes.empty()) {
			int node = startNodes.pop();
			if(rfs[node]) {
				continue;
			}

			rfs[node] = true;
			if(type[node] == 2) {
				continue;
			}
			for(int next : fwdEdges.get(node)) {
				startNodes.push(next);
			}
		}

		// find all nodes reachable from end nodes without visiting a start node
		// (traverse reverse edges)
		while(!endNodes.empty()) {
			int node = endNodes.pop();
			if(rfe[node]) {
				continue;
			}

			rfe[node] = true;
			if(type[node] == 1) {
				continue;
			}
			for(int next : revEdges.get(node)) {
				endNodes.push(next);
			}
		}

		for(int i = 0; i < numNodes; i++) {
			System.out.println(rfs[i] && rfe[i] ? "1" : "0");
		}
	}
}


import java.util.Arrays;
import java.util.Scanner;

public class Code624B {

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

		int n = scanner.nextInt();
		int[] a = new int[n];
		boolean[] f = new boolean[(int) (Math.pow(10, 9) + 1)];

		for(int i = 0; i < n; i++) {
			a[i] = scanner.nextInt();

			if(f[a[i]]) {
				for(int j = a[i] - 1; j >= 0; j--) {
					if(!f[j]) {
						a[i] = j;
						f[j] = true;
						break;
					}
				}
			} else
				f[a[i]] = true;
		}

		Arrays.sort(a);

		long count = 0;

		for (int i : a) {
			count += i;
		}

		System.out.println(count);

		scanner.close();
	}

}


import java.util.*;

// import javax.swing.text.DefaultStyledDocument.ElementSpec;

import java.io.*;

public class C{
    static int MOD = 1000000007;
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        PrintWriter out = new PrintWriter(System.out);
        int n = sc.nextInt();
        int x = sc.nextInt();
        int pos = sc.nextInt();
        int smaller = x-1;
        int larger = n-x;
        int left = 0;
        int right = n;
        long ans = 1;
        int noOfElementLeft = n-1;
        boolean zero = false;
        while(left<right){
            int mid = (left+right)/2;
            // if(mid==pos){

            //     ans = (ans*(fact(noOfElementLeft)))%MOD;
            //     break;
            // }
            else if(mid>=pos){
                if(larger==0){
                    zero=true;
                    break;
                }
                right = mid;
                ans = (ans*larger)%MOD;
                // ans = ans%MOD;
                larger--;
                noOfElementLeft--;
            }
            else{
                if(smaller==0){
                    zero=true;
                    break;
                }
                left = mid+1;
                ans = (ans*smaller)%MOD;
                smaller--;
                noOfElementLeft--;
            }

        }

        if(zero)out.println(0);
        else{
            out.println(ans);
        }

        out.close();
        sc.close();

    }
    public static long fact (int no){
        long ans = 1;
        while(no>0){
            ans = (ans*no)%MOD;
            no--;
        }
        return ans;
    }
}


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

public class Solution2 {
    public static void main(String[] args) throws IOException {
        MyScanner.init(System.in);
        String in = MyScanner.nextLine();
        int row = Integer.parseInt(String.valueOf(in.substring(0, in.length() - 1)));

        int count = 0;
        int blocks = (row-1)/4;
        count += blocks*16;
        int num = row%4;
        count += getServeTime(num);
        char c = in.charAt(in.length()-1);
        int seat = getSeat(c);
        count += seat;
        System.out.println(count);
    }

    private static int getServeTime(int num) {
        if(num %2 == 1){
            return 0;
        } else {
            return 7;
        }
    }

    private static int getSeat(char c) {
        if (c == 'f') {
            return 1;
        } else if (c == 'e') {
            return 2;
        } else if (c == 'd') {
            return 3;
        } else if (c == 'a') {
            return 4;
        } else if (c == 'b') {
            return 5;
        } else {
            return 6;
        }
    }

    static class MyScanner {
        static BufferedReader reader;
        static StringTokenizer tokenizer;

        static void init(InputStream input) {
            reader = new BufferedReader(new InputStreamReader(input));
            tokenizer = new StringTokenizer("");
        }

        public static String next() throws IOException {
            while (!tokenizer.hasMoreTokens()) {
                // TODO add check for eof if necessary
                tokenizer = new StringTokenizer(reader.readLine());
            }
            return tokenizer.nextToken();
        }

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

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

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

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


import java.util.*;

public class p735c{

	public static void main(String args[]){
	Scanner in=new Scanner(System.in);
	int fib[]=new int[100000000];
	fib[0]=1;fib[1]=1;
	long n=in.nextLong();
	long i,m=n-1;
	for(i=0;;)
	{
		if(i>=2)
		fib[(int)i]=fib[(int)i-1]+fib[(int)i-2];
		m=m-fib[(int)i];
		if(m>=0)
			i++;
		else break;
	}
	System.out.println(i);
}

}


import java.io.*;
import java.lang.reflect.Array;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class PC {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        long n =  scanner.nextLong();
        long[] dp =  new long[50000000];
        dp[0] = 0;
        dp[1] = 1;
        int i =  1;
        while (true){
            dp[i+1] = dp[i] + dp[i-1] + 1;
            if(dp[i+1] > n-1) break;
            i++;
        }
        System.out.println(i);

    }

}


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

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

    static class TaskC {
        public void solve(int testNumber, InputReader in, PrintWriter out) {
            long n = in.ni();
            long[] dp = new long[100000];
            dp[0] = 1;
            dp[1] = 2;
            for (int i = 1; ; ++i) {
                dp[i + 1] = dp[i] + dp[i - 1];
                if (dp[i + 1] > n) {
                    out.println(i);
                    return;
                }
            }
        }

    }

    static class InputReader {
        BufferedReader br;
        StringTokenizer st;

        public InputReader(InputStream inputStream) {
            br = new BufferedReader(new InputStreamReader(inputStream));
        }

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

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

    }
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class BOOL {
private static FastReader in =new FastReader();
    static String S,Sc;
    static int n,m=1,l=0;
    static long z=1,x,c;
    public static void main(String[] args) {
    x=in.nextLong();
    ArrayList <Integer>A=new ArrayList();
    A.add(2);
    A.add(3);
    for(int i=2;A.get(A.size()-1)<=x;i++){
    A.add(A.get(i-2)+A.get(i-1));

    }
    for(int i=0;;i++){
    if(A.get(i)<=x){c++;}
        else
        break;
    }
        System.out.println(c);
    }

static void shuffle(int[] a) {
		Random r = new Random();
		for(int i = a.length - 1; i > 0; --i) {
			int si = r.nextInt(i);
			int t = a[si];
			a[si] = a[i];
			a[i] = t;
		}
	}

	static int lower_bound(int[] a, int n, int k) {
		int s = 0;
		int e = n;
		int m;
		while (e - s > 0) {
			m = (s + e) / 2;
			if (a[m] < k)
				s = m + 1;
			else
				e = m;
		}
		return e;
	}
	static int lower_bound(long[] a, int n, long k) {
		int s = 0;
		int e = n;
		int m;
		while (e - s > 0) {
			m = (s + e) / 2;
			if (a[m] < k)
				s = m + 1;
			else
				e = m;
		}
		return e;
	}

	static int gcd(int a, int b) {
		return b == 0 ? a : gcd(b, a % b);
	}
	static long gcd(long a, long b) {
		return b == 0 ? a : gcd(b, a % b);
	}

}
class FastReader
    {
        BufferedReader br;
        StringTokenizer st;

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

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

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

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

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

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


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

public	 class template
	{
		private InputStream is;
		private PrintWriter pw;
		static char[][] ch;
		static int  x1,x2,y1,y2,n,m,h,k;
		static long dist[][];
		static boolean boo[][];

		void soln()
		{
			is = System.in;
			pw = new PrintWriter(System.out);
			long s = System.currentTimeMillis();
			solve();
			pw.close();
			pw.flush();
			// tr(System.currentTimeMillis() - s + "ms");
		}

		public static void main(String[] args) throws Exception
		{
			new Thread(null, new Runnable()
			{
				public void run()
				{
					try
					{
						// new CODEFORCES().soln();
					} catch (Exception e)
					{
						System.out.println(e);
					}
				}
			}, "1", 1 << 26).start();
			new template().soln();
		}

		void solve()
		{
			long l = ni(), r = ni(), x = ni(), y = ni();
			long mul = x*y;
			int cnt = 0;
			if(x==y && x>=l && x<=r) {pw.println(1);return;}
			long temp = Math.max(l,mul/r);
			temp += (((temp%x)==0)?0:x-(temp%x))
			for(long i = temp; i*i<=mul && i<= Math.min(r,mul/l);i+=x){
				//pw.println(i);
				if(mul%i==0 && gcd(i,mul/i)==x){
					//pw.println(i);
					if(mul/i != i) cnt+=2;
					else cnt++;
				}
			}
			pw.println(cnt);
			pw.close();
		}
		long gcd(long a, long b){
			if(b==0) return a;
			return gcd(b,a%b);
		}
		void printArray(long[] arr) {
			for(long i : arr) pw.print(i +" ");
			pw.println();
		}
	static long min(long x, long y){
		return (x<y)?x:y;
	}
	static class Pair implements Comparable<Pair>{
		long val;
		int  x, y;
		Pair(long v, int a, int b){
			val = v; x = a; y = b;
		}
		public int compareTo(Pair p){
			return Long.compare(this.val,p.val);
		}
	}
	private static class Queue{
		int st = 0;
		int et = 0;
		Pair[] arr;
		public Queue(int len) {
			arr = new Pair[len];
		}
		public boolean isEmpty() {
			return st==et;
		}
		public void add(Pair x) {
			arr[et++] = x;
		}
		public Pair poll() {
			return arr[st++];
		}
		public void clear() {
			st = et = 0;
		}
	}
		/*void bfs(int k) {
			while(!q.isEmpty()) {
				int y = q.poll();
				for(long i : amp[y]) {
					if(!b[i]) {
						D[i][k] = D[y][k]+1;
						q.add(i);
						b[i] = true;
					}
				}
			}
		}
		*/
		/*
		int dfs(int x) {
			b[x] = true;
			//start[x] = time++;
			int ans = 1;
			for(int i : amp[x]) {
				if(!b[i]) {
					ans += dfs(i);
				}
			}
			//end[x] = time;
			if(x!= 0 && ans%2==0 && (N-ans)%2==0) cost++;

			return ans;
		}*/

		/*void buildGraph(int n)
		{
			for (int i = 0; i < n; i++)
			{
				int x1 = ni() - 1, y1 = ni() - 1;
				amp[x1].add(y1);
				amp[y1].add(x1);
			}
		}*/
		public static int[] shuffle(int[] a, Random gen)
		{
			for (int i = 0, n = a.length; i < n; i++)
			{
				int ind = gen.nextInt(n - i) + i;
				int d = a[i];
				a[i] = a[ind];
				a[ind] = d;
			}
			return a;
		}
		// To Get Input
		// Some Buffer Methods
		private byte[] inbuf = new byte[1024];
		public int lenbuf = 0, ptrbuf = 0;

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

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

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

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

		private char nc()
		{
			return (char) skip();
		}

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

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

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

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

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

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

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

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

		private boolean oj = System.getProperty("ONLINE_JUDGE") != null;

		private void tr(Object... o)
		{
			if (!oj)
				System.out.println(Arrays.deepToString(o));
		}
	}


import java.util.*;
public class prob1
{
	public static int gcd(int a,int b){
		while(b!=0){
			int p = a%b;
			a=b;
			b=p;
		}
		return a;
	}

	public static void main (String[] args) throws java.lang.Exception
	{
		Scanner scan = new Scanner(System.in);
		int l = scan.nextInt();
		int r = scan.nextInt();
		int x = scan.nextInt();
		int y = scan.nextInt();
		int v =0;
		if(y%x==0){
		y = y/x;
		int v =0;
		for(int i=1;i<=Math.sqrt(y);i++){
			int p=y/i;
			if(y%i==0&&gcd(p,i)==1&&i>=l&&i<=r&&p>=l&&p<=r){
				if(p!=i){
					v=v+2;
				}
				else{
					v++;
				}
			}
		}
		}
		System.out.println(v);
	}
}


import java.util.*;
import java.lang.*;
import java.io.*;
public class B489{
	public static void main(String[] args) {
		InputReader fi=new InputReader(System.in);
		PrintWriter pr=new PrintWriter(System.out);
		long l=fi.nextLong();
		long r=fi.nextLong();
		long x=fi.nextLong();
		long y=fi.nextLong();
		long num=x*y;
		int cnt=0;
		for (int i=1; i<=Math.sqrt(num); i=i+x)
		{
			if (num%i==0)
			{
				if (num/i == i)
				{
					long m=i;
					if(l<=m&&m<=r&&m==x&&(m*m)==y){
						//pr.printf("%d  %d\n",m,m);
						cnt++;
					}
				}
				else
				{
					long m=i;
					long n=num/i;
					long gcdvalue=0;
					if(m<n)
						gcdvalue=gcd(n,m);
					else
						gcdvalue=gcd(m,n);

					long lcmvalue=n*m/gcdvalue;

					if(l<=m&&n<=r&&gcdvalue==x&&lcmvalue==y) {
						cnt++;
						//pr.printf("%d  %d\n",m,n);

					}
					if(l<=n&&m<=r&&gcdvalue==x&&lcmvalue==y) {
						cnt++;
						//pr.printf("%d  %d\n",n,m);
					}
				}

			}
		}

		pr.println(cnt);
		pr.close();
	}
	static long gcd(long a, long b) {
		while (b != 0) {
			long t = a;
			a = b;
			b = t % b;
		}
		return a;
	}
}

class InputReader {
	private InputStream stream;
	private byte[] buf = new byte[8192];
	private int curChar, snumChars;
	private SpaceCharFilter filter;

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

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

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

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

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

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

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

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


import java.util.*;
import java.io.*;
import java.lang.*;
import java.math.*;
public class C {
    public static int mod = 1000000007;
    public static void main(String[] args) throws Exception {
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
        // int n = Integer.parseInt(bf.readLine());
        StringTokenizer st = new StringTokenizer(bf.readLine());
        // int[] a = new int[n]; for(int i=0; i<n; i++) a[i] = Integer.parseInt(st.nextToken());
        int n = Integer.parseInt(st.nextToken());
        int k = Integer.parseInt(st.nextToken());
        long[] g = new long[n+1];
        for(int i=1; i<=k; i++) g[i] = 1;
        long sum = k;
        for(int i=k+1; i<=n; i++) {
          g[i] = sum * inv(i) % mod;
          sum += g[i];
          sum -= g[i-k];
          sum += mod;
          sum %= mod;
        }
        long[] nm = new long[n+1];
        nm[0] = 1;
        long[] fact = new long[n+1];
        fact[0] = 1;
        for(int i=1; i<=n; i++) {
          fact[i] = fact[i-1] * i % mod;
        }
        for(int i=1; i<=n; i++) {
          nm[i] = g[i] * fact[i] % mod;
        }
        //out.println(Arrays.toString(nm));
        long ans = 0;
        for(int i=0; i<n; i++) ans += nm[i] * inv((int)fact[i]) % mod;
        ans %= mod;
        ans *= fact[n-1];
        ans %= mod;
        ans = fact[n] - ans;
        ans += mod;
        ans %= mod;
        out.println(ans);
        out.close(); System.exit(0);
    }
    public static int exp(int base, int e) {
      if(e == 0) return 1;
      if(e == 1) return base;
      int val = exp(base, e/2);
      int ans = (int)(1L*val*val % mod);
      if(e % 2 == 1)
        ans = (int)(1L*ans*base % mod);
      return ans;
    }
    public static int inv(int base) {
      return exp(base, mod-2);
    }
}


import java.util.*;
import java.io.*;
import java.lang.*;
import java.math.*;
public class C {
    public static int mod = 1000000007;
    public static void main(String[] args) throws Exception {
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
        // int n = Integer.parseInt(bf.readLine());
        StringTokenizer st = new StringTokenizer(bf.readLine());
        // int[] a = new int[n]; for(int i=0; i<n; i++) a[i] = Integer.parseInt(st.nextToken());
        int n = Integer.parseInt(st.nextToken());
        int k = Integer.parseInt(st.nextToken());
        if(k>=n) k = n-1;
        long[] g = new long[n+1];
        for(int i=1; i<=k; i++) g[i] = 1;
        long sum = k;
        for(int i=k+1; i<=n; i++) {
          g[i] = sum * inv(i) % mod;
          sum += g[i];
          sum -= g[i-k];
          sum += mod;
          sum %= mod;
        }
        long[] nm = new long[n+1];
        nm[0] = 1;
        long[] fact = new long[n+1];
        fact[0] = 1;
        for(int i=1; i<=n; i++) {
          fact[i] = fact[i-1] * i % mod;
        }
        for(int i=1; i<=n; i++) {
          nm[i] = g[i] * fact[i] % mod;
        }
        //out.println(Arrays.toString(nm));
        long ans = 0;
        for(int i=0; i<n; i++) ans += nm[i] * inv((int)fact[i]) % mod;
        ans %= mod;
        ans *= fact[n-1];
        ans %= mod;
        ans = fact[n] - ans;
        ans += mod;
        ans %= mod;
        out.println(ans);
        out.close(); System.exit(0);
    }
    public static int exp(int base, int e) {
      if(e == 0) return 1;
      if(e == 1) return base;
      int val = exp(base, e/2);
      int ans = (int)(1L*val*val % mod);
      if(e % 2 == 1)
        ans = (int)(1L*ans*base % mod);
      return ans;
    }
    public static int inv(int base) {
      return exp(base, mod-2);
    }
}


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.StringTokenizer;

public class Div1_445C {

	static long MOD = 1_000_000_007;

	static long[] fact;
	static long[] iFact;

	public static void main(String[] args) throws IOException {
		BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
		PrintWriter printer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
		StringTokenizer inputData = new StringTokenizer(reader.readLine());
		int n = Integer.parseInt(inputData.nextToken());
		int k = Integer.parseInt(inputData.nextToken());

		if (k >= n - 1) {
			printer.println(0);
			printer.close();
			return;
		}

		fact = new long[n + 1];
		fact[0] = 1;
		for (int i = 1; i <= n; i++) {
			fact[i] = i * fact[i - 1] % MOD;
		}

		iFact = new long[n + 1];

		iFact[n] = pow(fact[n], MOD - 2);
		for (int i = n - 1; i >= 1; i--) {
			iFact[i] = (i + 1) * iFact[i + 1] % MOD;
		}

		long[] f = new long[n + 1];
		long[] preG = new long[n + 1];

		for (int i = k + 1; i <= n; i++) {
			f[i] = ((i - k - 1) * fact[i - 2]
					+ fact[i - 2] * (preG[i - 1] - (i - k - 1 >= 0 ? preG[i - k - 1] : 0) + MOD)) % MOD;
			preG[i] = (preG[i - 1] + f[i] * iFact[i - 1]) % MOD;
		}

		long ans = 0;
		// i is position where we put the greatest element
		for (int i = 1; i <= n; i++) {
			ans = (ans + f[i] * fact[n - 1] * iFact[i - 1]) % MOD;
		}
		printer.println(ans);
		printer.close();
	}

	static long pow(long base, long exp) {
		base %= MOD;
		long ans = 1;
		while (exp > 0) {
			if ((exp & 1) == 1) {
				ans = ans * base % MOD;
			}
			base = base * base % MOD;
			exp >>= 1;
		}
		return ans;
	}
}


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

public class Main{

    void solve() {
        int n=ni(),k=ni();
        pre(n);
        long pref[]=new long[n+1];
        long dp[]=new long[n+1];
        for(int i=k+1;i<=n;i++){
            dp[i]=i-k-1;
            dp[i]=add(dp[i],sub(pref[i-1],pref[i-k-1],M),M);
            dp[i]=mul(dp[i],fact[i-2],M);

            pref[i]=add(pref[i-1],mul(dp[i],inv[i-1],M),M);
        }
        long ans=0;
        for(int i=1;i<=n;i++){
            ans=add(ans,mul(dp[i],inv[i-1],M),M);
        }
        ans=mul(ans,fact[n-1],M);
        pw.println(ans);

    }
    long fact[];
    long inv[];
    long add(long x,long y,long M){
        x+=y;
        if(x>=M) x-=M;
        return x;
    }
    long sub(long x,long y,long M){
        x-=M;
        if(x<0) x+=M;
        return x;
    }

    long ncr(int n,int r){
        long ans=fact[n];
        ans=mul(ans,inv[n-r],M);
        ans=mul(ans,inv[r],M);
        return ans;
    }
    void pre(int n){
        fact=new long[n+1];
        inv=new long[n+1];
        fact[0]=1;
        for(int i=1;i<=n;i++) fact[i]=(fact[i-1]*i)%M;
        inv[n]=modInverse(fact[n],M);
        for(int i=n-1;i>=0;i--) inv[i]=(inv[i+1]*(i+1))%M;
    }
    long mul(long a, long b,long M)
    {
        return (a*1L*b)%M;
    }
    long modpow(long a, long b,long M)
    {
        long r=1;
        while(b>0)
        {
            if((b&1)>0) r=mul(r,a,M);
            a=mul(a,a,M);
            b>>=1;
        }
        return r;
    }

    long modInverse(long A, long M)
    {

        return modpow(A,M-2,M);
    }

    long M=(long)1e9+7;
    InputStream is;
    PrintWriter pw;
    String INPUT = "";
    void run() throws Exception {
        is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
        pw = new PrintWriter(System.out);
        long s = System.currentTimeMillis();
        solve();
        pw.flush();
        if(!INPUT.isEmpty())tr(System.currentTimeMillis()-s+"ms");
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

    private void tr(Object... o) { if(INPUT.length() > 0)System.out.println(Arrays.deepToString(o)); }
}


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package codeforces;
import java.util.*;
/**
 *
 * @author elbrh
 */
public class B344 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        Scanner sc = new Scanner(System.in);
        StringBuilder out = new StringBuilder();
        int a,b,c ;
        a = sc.nextInt();
        b= sc.nextInt();
        c = sc.nextInt();
        int res = a+b+c ;
        if(res%2 == 0){
            res /= 2 ;
            int x = res - c ;
            int z = res - b ;
            int y = res - a ;
            if(x >= 0 && y >= 0 && z >= 0){
                System.out.println(x +" "+y+" "+z);
            }
            else
                System.out.println("Impossible");

        }
    }

}


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

public class Main {
    public void solve() {
        int a = ni(), b = ni(), c = ni(), l = ni();
        int x, y ,z;
        if ((a > b) && (a > c)) {
            x = a;
            if (b > c) {
                y = b;
                z = c;
            } else {
                y = c;
                z = b;
            }
        } else if (b > c) {
            x = b;
            if (a > c) {
                y = a;
                z = c;
            } else {
                y = c;
                z = a;
            }
        } else {
            x = c;
            if (b > a) {
                y = b;
                z = a;
            } else {
                y = a;
                z = b;
            }
        }

        long ans = 0;
        for (int i = x; l - (i - x) - (Math.max(0, i - (y + z) + 1)) >= 0; i++) {
            for (int j = y; l - (i - x) - (j - y) - (Math.max(0, j - (i + z) + 1)) >= 0; j++) {
//                System.out.println(i + " " + j + " " + (l - (i - x) - (j - y)));
                int max = (i + j - 1);
                int min = Math.abs(i - j) + 1;
//                System.out.println("min: " + min + " max: " + max);
                int steps = l - (i - x) - (j - y) - Math.max(0, min - z);
                min = Math.max(min, z);
                max = Math.min(max, min + steps);
                ans += Math.max(0, max - min + 1);
//                System.out.println(Math.max(0, max - min + 1));
            }
        }
        write(ans + "\n");
    }

    public static void main(String[] args){
        Main m = new Main();
        m.solve();
        try {
            m.writer.close();
        } catch (IOException e) {};
    }
    BufferedReader reader;
    BufferedWriter writer;
    StringTokenizer tokenizer;
    public Main() {
        reader = new BufferedReader(new InputStreamReader(System.in));
        writer = new BufferedWriter(new OutputStreamWriter(System.out));
    }
    int ni() {
        return Integer.parseInt(n());
    }
    String n() {
        if (tokenizer == null || !tokenizer.hasMoreTokens()) {
            try {
                tokenizer = new StringTokenizer(reader.readLine());
            } catch (IOException e) {}
        }
        return tokenizer.nextToken();
    }
    void write(String s) {
        try {
            writer.write(s);
        } catch(IOException e) {};
    }
}


import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.PriorityQueue;
import java.util.Scanner;

public class Main {
	public static long solve(long a,long b,long c,long lest) {
		if(a<b+c) return  0;
		if(a-b-c<lest) lest=a-b-c;
		return (lest+1)*(lest+2)/2;
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner in=new Scanner(System.in);
		long a,b,c,I;
		long res[]=new long[300005];
		while(in.hasNext())
		{
			a=in.nextLong();
			b=in.nextLong();
			c=in.nextLong();
			I=in.nextLong();
			res[0]=1;
			long ans=0;
			for(int i=1;i<=I;i++){
				long x=i;
				res[i]=(x+1)*(x+2)/2+res[i-1];
				if(i==I) ans=res[i];
			}
			for(int i=0;i<=I;i++) {
				ans-=solve(a+i,b,c,I-i);
				ans-=solve(b+i,a,c,I-i);
				ans-=solve(c+i,a,b,I-i);
			}
			System.out.println(ans);
		}
	}
}
/*
1 1 1 2
1 2 3 1
10 2 1 7
*/


import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;

public class Main {
	static ArrayList<Integer> aa;

	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		int n = in.nextInt();
		int k = in.nextInt();
		aa = new ArrayList<Integer>(2500);
		dfs(7);
		dfs(4);
		int nn = n;
		if (n < 13 && k > fact(n))
			System.out.println(-1);
		int l = Math.min(13, n);
		int[] a = new int[l];
		boolean[] v = new boolean[l];
		for (int i = 0; i < a.length; i++)
			a[i] = n - i;
		Arrays.sort(a);
		int[] ans = new int[a.length];
		long g;
		long kk = k;
		long f;
		boolean d;
		for (int i = 0; i < a.length; i++) {
			g = kk / (f = fact(n - 1)) + 1;
			if (kk % f == 0)
				g--;
			int cnt = 0, j;
			for (j = 0; j < a.length; j++) {
				if (!v[j])
					cnt++;
				if (cnt == g)
					break;
			}
			v[j] = true;
			ans[i] = a[j];
			d = false;
			if (kk >= f)
				d = true;
			kk %= f;
			if (d && kk == 0)
				kk += f;
			n--;
		}
		int ret = 0;
		for (int i = 0; i < ans.length; i++)
			if (aa.contains(ans[i]) && aa.contains(i + nn - l + 1))
				ret++;
		System.out.println(ret);
	}

	public static long fact(long n) {
		if (n == 1 || n == 0)
			return 1;
		return n * fact(n - 1);
	}

	public static void dfs(long n) {
		if (n > 1000000000)
			return;
		aa.add((int) n);
		dfs(n * 10 + 4);
		dfs(n * 10 + 7);
	}
}


import javax.sound.sampled.Line;
import java.awt.Point;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.io.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import static java.math.BigInteger.*;

import java.math.MathContext;
import java.util.*;
public class C{

      ArrayList<Long>all;
    void solve()throws Exception
    {

        all=new ArrayList<Long>();
        get(0,(long)7777777777L);
        Collections.sort(all);
        ArrayList<Integer>a=new ArrayList<Integer>();
        int n=nextInt();
        long k=nextInt();
        long z=1;
        for(int i=1;i<=n;i++)
        {
            z*=i;
            if(z>=k)
                break;
        }
        if(z<k)
        {
            System.out.println(-1);
            return;
        }
        while (a.size()<11 && n>0)
        {
            a.add(n);
            n--;
        }
        Collections.reverse(a);
        int res=0;
        for(Long x: all)
            if(x<=n)
                res++;
        long[]fact=new long[a.size()];
        for(int i=0;i<fact.length;i++)
            if(i==0)
                fact[i]=1;
            else
                fact[i]=i*fact[i-1];
        boolean []used=new boolean[a.size()];
        int[]x=new int[used.length];
        for(int at=0;at<a.size();at++)
        {

            long who=0;
            while (k>fact[a.size()-1-at])
            {
                k-=fact[a.size()-1-at];
                who++;
            }

            int ans=-1;
            for(int i=0;i<a.size();i++)
                if(!used[i])
                {
                    who--;
                    if(who==-1)
                    {
                        ans=i;
                        break;
                    }
                }
            used[ans]=true;
            x[at]=a.get(ans);
            //System.out.println(x[at]);
        }
        for(int i=0;i<a.size();i++)
        {
            if(all.indexOf((long)x[i])>=0 && all.indexOf((long)(i+1+n))>=0)
                res++;
        }
        System.out.println(res);

    }
    void get(long cur,long max)
    {
        if(cur>max)
            return;
        if(cur!=0)
            all.add(cur);
        get(10*cur+4,max);
        get(10*cur+7,max);

    }

    ////////////
    BufferedReader reader;
    PrintWriter writer;
    StringTokenizer stk;
    void run()throws Exception
    {
        reader=new BufferedReader(new InputStreamReader(System.in));
        stk=null;
        writer=new PrintWriter(new PrintWriter(System.out));
        solve();
        reader.close();
        writer.close();
    }
    int nextInt()throws Exception
    {
        return Integer.parseInt(nextToken());
    }

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

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

    }

    String nextString()throws Exception
    {
        return nextToken();
    }
    String nextLine()throws Exception
    {
        return reader.readLine();
    }
    String nextToken()throws Exception
    {
        if(stk==null || !stk.hasMoreTokens())
        {
            stk=new StringTokenizer(nextLine());
            return nextToken();

        }
        return stk.nextToken();
    }

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

}


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

public class LuckyPermutation {

	static class Scanner{
		BufferedReader br=null;
		StringTokenizer tk=null;
		public Scanner(){
			br=new BufferedReader(new InputStreamReader(System.in));
		}
		public String next() throws IOException{
			while(tk==null || !tk.hasMoreTokens())
				tk=new StringTokenizer(br.readLine());
			return tk.nextToken();
		}
		public int nextInt() throws NumberFormatException, IOException{
			return Integer.valueOf(next());
		}
	}

	static long[] fact = new long[14];

	static void init(){
		fact[0] = 1;
		for(int i = 1; i <= 13; i++)
			fact[i] = fact[i - 1]*i;
		return;
	}

	static boolean islucky(int num){
		char[] n = (num+"").toCharArray();
		for(int i = 0; i < n.length; i++)
			if (n[i]!='4' && n[i]!='7')
				return false;
		return true;
	}

	public static void main(String args[]) throws NumberFormatException, IOException{
		Scanner sc = new Scanner();
		init();
		int N = sc.nextInt();
		int K = sc.nextInt();
		LinkedList<Integer> ans = new LinkedList<Integer>();
		if (N <= 13 && fact[N] < K){
			System.out.println("-1");
			return;
		}
		for(int i = 1; i <= N - 13; i++)
			ans.add(i);
		TreeSet<Integer> current = new TreeSet<Integer>();
		for(int i = Math.max(1, N - 12); i <= N; i++)
			current.add(i);
		int limit = current.size();
		for(int i = 0; i < limit; i++){
			int index = 1;
			for(int e: current){
				if (fact[current.size() - 1]*index >= K){
					K -= fact[current.size() - 1] * (index - 1);
					current.remove(e);
					ans.add(e);
					break;
				}
				index++;
			}
		}
		int index = 1;
		int amount = 0;
		for(int e: ans){
			if (islucky(index) && islucky(e))
				amount++;
			index++;
		}
		System.out.println(amount);
	}

}


import java.io.*;
import java.util.*;
import java.lang.reflect.Array;
import java.math.*;
public class lucksum {
	public static long go(long m)
	{
		long res=0;
		Queue<Long> l=new LinkedList<Long>();
		l.add(new Long(0));
		do{
			Long t=l.remove();
			if(t.compareTo(new Long(m))<=0)
			{
				res++;
				l.add(t*10+4);
				l.add(t*10+7);
				}
			else
				break;

		}while(true);

		return res-1;
	}
	public static boolean isluck(long m)
	{
		boolean res=true;
		while(m!=0)
		{
			long t=m%10;
			if((t!=4)&&(t!=7))
				return false;
			m/=10;
		}
		return res;

	}
	public static void main(String[] args)
	{

		//try{
			Scanner s=new Scanner(System.in);
			long n=s.nextLong();
			long k=s.nextLong();
			long []p=new long[21];
			Arrays.fill(p,Long.MAX_VALUE);
			long start=1;
			long mul=2;
			p[0]=1;
			while(start<=k)
			{
				p[(int)mul-1]=start;
				start*=mul;
				mul++;
			}
			if((n<20)&&(p[(int)n]<k))
			{
				System.out.println(-1);
				return;
			}
			int index=0;
			for(;p[index]<k;index++);
	//		index++;
			long res=go(n-index);

			List<Long> left=new LinkedList<Long>();
			for(int i=index-1;i>=0;i--)
				left.add(n-i);

			while(index>0)
			{
				Long[] mm=(Long[])left.toArray(new Long[left.size()]);

				long t=k/p[index-1];
				if(k==1)
					t=0;
				long h=mm[(int)t];
				if(isluck(h)&&isluck(n-index+1))
					res++;
				left.remove((int)t);
				k%=p[index-1];
				index--;

			}
			System.out.println(res);

	//	}catch (Exception e1){

		//}

	}
}


import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;

public class C {
    static int e;
    static long count;

    public static void construct(int l, String cur) {
        if (l == 0) {
            if (Integer.parseInt(cur) <= e) {
                count++;
            }
            return;
        }
        construct(l - 1, cur + "4");
        construct(l - 1, cur + "7");
    }

    public static long getLuckCount(int end) {
        int length = ("" + end).length();
        long res = 0;
        for (int i = 1; i < length; i++) {
            res += (1 << i);
        }
        e = end;
        count = 0;
        construct(length, "");
        res += count;
        return res;
    }

    public static boolean isLucky(int numb) {
        while (numb > 0) {
            int mod = numb % 10;
            if (mod != 4 && mod != 7)
                return false;
            numb /= 10;
        }
        return true;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int k = sc.nextInt();
        int idx = n;
        long cur = 1L;
        while (true) {
            if (cur >= k) {
                break;
            }
            idx--;
            if (idx < 1) {
                break;
            }
            cur *= (n - idx + 1);
        }
        cur /= (n - idx + 1);
        if (idx < 1) {
            System.out.println(-1);
        }
        ArrayList<Integer> list = new ArrayList<Integer>();
        for (int i = idx; i <= n; i++) {
            list.add(i);
        }
        int tmpIdx=idx;
        int[] res = new int[n - idx + 1];
        int curSto = 0;
        while (list.size()>0) {
            long req = (long) Math.ceil((k*1.0) / cur);
            //System.out.println(k+" "+cur);
            res[curSto] = list.get((int) (req - 1));

            list.remove((int)(req-1));
            //System.out.println(Arrays.toString(res)+" "+list.size());
            curSto++;
            k = (int) (k % cur);
            if(k==0){
                k=(int) cur;
            }
            tmpIdx++;

            //System.out.println(k+" "+cur+" "+tmpIdx);
            if(n-tmpIdx+1!=0)
            cur=cur/(n-tmpIdx+1);
        }
        int print = 0;
        for (int i = 0, j = idx; i < res.length; i++, j++) {
            if (isLucky(j) && isLucky(res[i]))
                print++;
        }
        if (idx > 0)
            print += getLuckCount(idx - 1);
        System.out.println(print);
    }
}


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

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

class Task23
{
	Scanner in;

	int[] getPermutation ( int[] a, long k )
	{
		boolean seen[] = new boolean[a.length];
		int r[] = new int[a.length];
		Arrays.fill ( r, -1 );
		for ( int i = 0; i < a.length; ++i )
		{
			long fact = 1;
			for ( int j = 1; j < a.length-i; ++j )
				fact *= j;
			long id = (k-1) / fact;
			k -= id*fact;
			for ( int j = 0; j < a.length; ++j )
				if ( !seen[j] )
				{
					if ( id == 0 ) {
						r[i] = a[j];
						seen[j] = true;
						break;
					}
					id--;
				}
		}
		return r;
	}

	boolean isLucky ( int n ) {
		for ( ; n > 0; n /= 10 )
			if ( n%10 != 4 && n%10 != 7 )
				return false;
		return true;
	}

	public void solve ( ) throws Exception
	{
		in = new Scanner ( System.in );
		int n = in.nextInt();
		long k = in.nextLong();

		if ( n <= 15 )
		{
			long fact = 1;
			for ( int i = 1; i <= n; ++i )
				fact *= i;
			if ( k > fact )
			{
				println ( "-1\n" );
				return;
			}
		}

		int last[] = new int[Math.min(15,n)];
		for ( int i = 0; i < last.length; ++i )
			last[i] = n-last.length+i+1;

		last = getPermutation ( last, k );
		int a[] = new int[n];
		for ( int i = 0; i < n; ++i )
			if ( i+last.length >= n )
				a[i] = last[i-(n-last.length)];
			else
				a[i] = i+1;

		int ans = 0;
		for ( int i = 0; i < n; ++i )
			if ( isLucky(i+1) && isLucky(a[i]) )
				ans++;
		println ( ans );
	}

	public static void println ( Object o ) { System.out.println ( o ); }
	public static void print ( Object o ) { System.out.print ( o ); }
	public static void println ( ) { System.out.println ( ); }
}


// 327A
import java.util.Scanner;

/*
*To get max zeroes count,treat 0 as -1 and 1 as +1
*now we have to get max contiguous sequence of zeroes(+1) having max +ve sum
*Then it can be easily solved by Kadane's algorithm of max contiguous sum
*/
//-->YouTube link for KADANE ALGO	https://youtu.be/86CQq3pKSUw

public class FlippingGame_KADANEalgo {
	public static void main(String[] args) {
		int[] a;
		int current_max=0,global_max=0;
		int i,rev,t_ones=0;
		Scanner sc = new Scanner(System.in);
		int n=sc.nextInt();
		a=new int[n];
		for(i=0;i<n;i++) {
			a[i]=sc.nextInt();
			t_ones+=a[i];
			rev=-2*a[i]+1;// 1 ==> -1 and 0 ==> 1
			current_max = Math.max(rev,rev+current_max); //now get max contiguous sum in array using Kadane's Algo
			global_max=Math.max(global_max,current_max); //update 'global_max' only when it is LESS than 'current_max'
		}
		sc.close();
		System.out.println(t_ones+global_max);
	}
}


package maraton;

import java.util.Scanner;

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

        long a =sca.nextLong();
        long b =sca.nextLong();
        if (b<a)
        {
            System.out.println(0);
        }else{
         if(a==0)
        {
        a=2;
        }
         else if  (a==1)
        {
            a++;
        }

        long pivote=2L;
        int niveles = 0,base,totales=0;
        while (pivote <= a)
        {
            pivote = (pivote * 2) + 1;
            niveles++;
        }
        pivote = (pivote - 1) / 2;

        if (pivote == a)
        {
            totales++;

        }

        base = niveles - 2;

        while (base >= 0 && pivote <= b)
        {

            pivote = pivote + (long) (Math.pow(2, base));
            base--;

            if (pivote >= a && pivote<=b)
            {

                totales++;
            }

        }
        long  pivote2 = 2;
        int niveles2=0,cont2=0;

        while (pivote2 <= b)
        {
            pivote2 = (pivote2   *  2)  +  1;
            niveles2++;
        }
        pivote2 = (pivote2 - 1) / 2;
        base = niveles2 - 2;

        if (niveles2 > niveles)
        {
            while (pivote2 <= b && base>=0)
            {
                cont2++;
                if (pivote2 + Math.pow(2, base) <= b)
                {

                    pivote2 = pivote2 + (int) Math.pow(2, base);
                    base--;
                    if (base==-1 && pivote2<b) {
                        cont2++;
                    }

                } else
                {

                    break;

            }
        }

        }
        System.out.println("final: " + (totales + cont2+ contadorFilas(niveles, niveles2)));

    }
    }
     static int contadorFilas(int nivelA,int nivelB)
{
    int acu=0;
    for (int i = nivelA; i < nivelB -1; i++)
    {
        acu+=++nivelA;
    }
    return acu;
}
}


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package arr_codeforces_goodbye2015_b;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Scanner;

/**
 *
 * @author Asprak70
 */
public class ARR_CodeForces_GoodBye2015_B {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        Scanner scan = new Scanner(System.in);
        Integer awal = scan.nextInt();
        Integer akhir = scan.nextInt();
        Integer sum = 0;
        String binerAwal = Integer.toString(awal,2);
        String binerAkhir = Integer.toString(akhir,2);
        for (int i = 0; i < (binerAwal.length() + binerAkhir.length()); i++){
            String x = "";
            if (i < binerAwal.length()){
                for (int j = 0; j < binerAwal.length(); j++){
                    if (j == i) x += "0"; else x += "1";
                }
                int dec = Integer.parseInt(x,2);
                if ((dec >= awal) && (dec <= akhir) && (x.charAt(0) != '0'))  {
                    sum++;
                }
            }else {
                for (int j = 0; j < binerAkhir.length(); j++){
                    if (j == (i-binerAwal.length())) x += "0"; else x+= "1";
                }
                int dec = Integer.parseInt(x,2);
                if ((dec >= awal) && (dec <= akhir) && (x.charAt(0) != '0')) {
                    sum++;
                }
            }
        }
        System.out.println(sum);
    }

}


import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.StringTokenizer;

public class B {
    static BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
    static PrintWriter pw = new PrintWriter(System.out);
    public static double func(double x, double n){

        return -n*(n*n-3*n-3*x*x+9*x-4)/(2*(x-2)*(x-1)*x);
    }
    public static void main(String[] args) throws IOException {
        StringTokenizer st = new StringTokenizer(r.readLine());
        ArrayList<Integer> nums = new ArrayList<>();
        int x = Integer.parseInt(st.nextToken());
        double p = Double.parseDouble(st.nextToken());
        int ans = 1;
        for(int i = 1; i<=x; i++){
            if(func(x,i)  >= p){
                ans = i;
                break;
            }
        }
        pw.print(ans);
        pw.close(); // make sure to include this line -- closes io and flushes the output
    }
}


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

public class I {

    public static boolean DEBUG = true;
    public static String name = "I";

    public static void main(String[] args) throws IOException {
    	FastScanner scan;
    	PrintWriter out;
    	if (DEBUG) {
    		scan = new FastScanner(System.in);
        	out = new PrintWriter(System.out);
    	}
    	else {
        	scan = new FastScanner(name + ".in");
        	out = new PrintWriter(new BufferedWriter(new FileWriter(name + ".out")));
    	}

		float N = Float.parseFloat(scan.nextString());
		float P = Float.parseFloat(scan.nextString());

        for(int i=0; i<=N; i+=1) {

            double val = i*(i-1)*(i-2)/6 + i*(i-1)*(N-i)/2 + *i*(N-i)*(N-i-1)/4;
            val = val / (N*(N-1)*(N-2)/6);

            if(val >= P) {
                out.println((int)i);
                break;
            }
        }

        out.close();
    }

    static class BIT {
        public int[] tree;

        public BIT(int len) {
          tree = new int[len+5];
        }

        // updates tree by adding val to index
        public void update(int index, int val) {
          index++;
          while(index < tree.length) {
            tree[index] ^= val;
            index += index & -index;
          }
        }

        public int query(int index) {
          int result = 0;
          index++;
          while(index > 0) {
            result ^= tree[index];
            index -= index & -index;
          }

          return result;
        }

        public int rangeSum(int low, int high) {
          return query(high) - query(low-1);
        }

      }

    /* BINARY LIFTING - Preprocess O(NlogN) - Query O(logN)*/
    static ArrayList<Integer>[] adjList;
    static int[] tin, tout;
    static int[][] BL;
    static int ct;

    public static void preprocess(int root) {
        ct = 0;
        tin = new int[adjList.length];
        tout = new int[adjList.length];
        BL = new int[adjList.length][log2(adjList.length)+1];

        recur_bl(root,root);
    }

    public static void recur_bl(int v, int p) {
        tin[v] = ++ct;
        BL[v][0] = p;
        for (int i=1; i <= log2(adjList.length); ++i) BL[v][i] = BL[BL[v][i-1]][i-1];

        for (int i=0; i<adjList[v].size(); i++) if(adjList[v].get(i) != p) recur_bl(adjList[v].get(i), v);

        tout[v] = ++ct;
    }

    public static boolean is_ancestor(int u, int v) {
        return tin[u] <= tin[v] && tout[u] >= tout[v];
    }

    public static int lca(int u, int v) {
        if(is_ancestor(u, v)) return u;
        if(is_ancestor(v, u)) return v;

        for(int i=log2(adjList.length); i >= 0; --i) if(!is_ancestor(BL[u][i], v)) u = BL[u][i];

        return BL[u][0];
    }

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

    static class FastScanner {

		// Is your Fast I/O being bad?

		InputStream dis;
		byte[] buffer = new byte[1 << 17];
		int pointer = 0;

		public FastScanner (String fileName) throws IOException {
			dis = new FileInputStream(fileName);
		}

		public FastScanner (InputStream is) throws IOException {
			dis = is;
		}

		int nextInt() throws IOException {
			int ret = 0;

			byte b;
			do {
				b = nextByte();
			} while (b <= ' ');
			boolean negative = false;
			if (b == '-') {
				negative = true;
				b = nextByte();
			}
			while (b >= '0' && b <= '9') {
				ret = 10 * ret + b - '0';
				b = nextByte();
			}

			return (negative) ? -ret : ret;
		}

		long nextLong() throws IOException {
			long ret = 0;

			byte b;
			do {
				b = nextByte();
			} while (b <= ' ');
			boolean negative = false;
			if (b == '-') {
				negative = true;
				b = nextByte();
			}
			while (b >= '0' && b <= '9') {
				ret = 10 * ret + b - '0';
				b = nextByte();
			}

			return (negative) ? -ret : ret;
		}

		byte nextByte() throws IOException {
			if (pointer == buffer.length) {
				dis.read(buffer, 0, buffer.length);
				pointer = 0;
			}
			return buffer[pointer++];
		}

		String nextString() throws IOException {
			StringBuffer ret = new StringBuffer();

			byte b;
			do {
				b = nextByte();
			} while (b <= ' ');
			while (b > ' ') {
				ret.appendCodePoint(b);
				b = nextByte();
			}

			return ret.toString();
		}

	}
}


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

public class Codeforces
{
    public static void main(String args[])throws Exception
    {
        BufferedReader bu=new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb=new StringBuilder();
        String s[]=bu.readLine().split(" ");
        int n=Integer.parseInt(s[0]);
        int i; double p=Double.parseDouble(s[1]);

        for(i=1;i<=n;i++)
        if(probab(n,i)>=p) break;
        System.out.println(i);
    }

    static int ncr(int n,int r)
    {
        if(r>n) return 0;
        int ans=1,i;
        for(i=n;i>n-r;i--) ans*=i;
        for(i=2;i<=r;i++) ans/=i;
        return ans;
    }

    static double probab(int n,int x)
    {
        int a=ncr(x,3)*ncr(n-x,0);
        int b=ncr(x,2)*ncr(n-x,1);
        int c=ncr(x,1)*ncr(n-x,2);
        return 1.0*((3.0/6)*c+a+b)/ncr(n,3);
    }
}


import java.util.Scanner;

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

        solve(s.nextInt(), (int)s.nextDouble() * 10000);
    }

    public static void solve(long n, long p) {
        long studied = 0;
        long notStudied = n;

        long zero;
        long one;
        long two;
        long three;

        long thisP;

        while (true) {
            zero = notStudied * (notStudied - 1) * (notStudied - 2) / 6;
            one = studied * notStudied * (notStudied - 1) / 2;
            two = studied * (studied - 1) * notStudied / 2;
            three = studied * (studied - 1) * (studied - 2) / 6;

            thisP = zero * 0 + one * 1 + two * 2 + three * 2;
            if (thisP * 5000 >= p * n * (n - 1) * (n - 2) / 6) {
                System.out.println(studied);
                return;
            }

            studied++;
            notStudied--;
        }
    }
}


import java.util.*;
import java.io.*;
public class F {

	static long mod = 998244353;
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int m = sc.nextInt();

		String[] s = new String[n];
		for(int i = 0; i < n; i++) {
			s[i] = sc.next();
		}

		HashSet<String> prefs = new HashSet<>();
		for(int i = 0; i < n; i++){
			for(int j = 1; j < s[i].length(); j++){
				prefs.add(s[i].substring(j));
			}
		}
		prefs.add("");
		HashSet<Pair> nodes = new HashSet<>();
		for(String a: prefs){
			for(String b: prefs){
				if(isPref(a, b)) {
					nodes.add(new Pair(a, b));
				}
			}
		}
		int N = nodes.size();
		HashMap<Pair, Integer> code = new HashMap<>();
		Pair[] decode = new Pair[N];
		int count = 0;
		for(Pair p: nodes) {
			decode[count] = p;
			code.put(p, count++);
		}
		long[][] aut = new long[N][N];
		Pair p0 = new Pair("","");
		for(String t: s) {
			for(String u: s) {
				if(isPref(t, u)) {
					String a = t.substring(1);
					String b = u.substring(1);
					Pair p = new Pair(a, b);
					aut[code.get(p0)][code.get(p)]++;
				}
			}
		}
		for(Pair p: nodes) {
			Pair q = next(p);
			if(p.equals(p0)){
				continue;
			}
			else if(q != null) {
				aut[code.get(p)][code.get(q)]++;
			}
			else {
				for(String t: s) {
					q = next(p, t);
					if(q != null && nodes.contains(q)) {
						aut[code.get(p)][code.get(q)]++;
					}
				}
			}
		}
		Matrix mat = new Matrix(aut);
		Matrix matp = pow(mat, m);
		System.out.println(matp.mat[code.get(p0)][code.get(p0)]);
	}
	static Pair next(Pair p, String s) {
		if(p.a.equals("")) {
			if(isPref(s, p.b)) {
				String a = s.substring(1);
				String b = p.b.substring(1);
				return new Pair(a, b);
			}
			else return null;
		}
		else if(p.b.equals("")) {
			if(isPref(s, p.a)) {
				String a = p.a.substring(1);
				String b = s.substring(1);
				return new Pair(a, b);
			}
			else return null;
		}
		else return null;
	}
	static Pair next(Pair p) {
		if(p.a.equals("")) return null;
		if(p.b.equals("")) return null;
		String a = p.a.substring(1);
		String b = p.b.substring(1);
		return new Pair(a, b);
	}
	static boolean isPref(String a, String b) {
		if(a.length() == b.length()) {
			return a.equals(b);
		}
		else if(a.length() > b.length()) {
			return b.equals(a.substring(0, b.length()));
		}
		else {
			return a.equals(b.substring(0, a.length()));
		}
	}
	static class Pair {
		String a, b;
		public Pair(String a, String b) {
			this.a = a; this.b = b;
		}
		@Override
		public int hashCode() {
			return a.hashCode() + b.hashCode();
		}
		@Override
		public boolean equals(Object o) {
			Pair p = (Pair)o;
			return a.equals(p.a) && b.equals(p.b);
		}
		public String toString() {
			return "'"+a+"' '"+b;
		}
	}

	static Matrix pow(Matrix m, int exp) {
		Matrix res = new Matrix(m.n);
		Matrix mapow = m;
		while(exp > 0) {
			if((exp & 1) == 1) {
				res = res.mult(mapow);
			}
			mapow = mapow.mult(mapow);
			exp >>= 1;
		}
		return res;
	}
	static class Matrix{
		long[][] mat; int n;
		public Matrix(long[][] mat) {
			n = mat.length;
			this.mat = mat;
		}
		public Matrix(int n) {
			mat = new long[n][n];
			this.n = n;
			for(int i = 0; i < n; i++) mat[i][i] = 1;
		}
		Matrix mult(Matrix m) {
			long[][] res = new long[n][n];
			for(int k = 0; k < n; k++) {
				for(int i = 0; i < n; i++) {
					for(int j = 0; j < n; j++) {
						res[i][j] += mat[i][k] * m.mat[k][j] % mod;
						res[i][j] %= mod;
					}
				}
			}
			return new Matrix(res);
		}
		public String toString(){
			StringBuilder sb = new StringBuilder();
			for(int i = 0; i < n; i++) {
				sb.append(Arrays.toString(mat[i])+"\n");
			}
			return sb.toString();
		}
		long[] mult(long[] vec) {
			long[] res = new long[n];
			for(int i = 0; i < n; i++) {
				for(int j = 0; j < n; j++) {
					res[i] += vec[j] * mat[i][j] % mod;
					res[i] %= mod;
				}
			}
			return res;
		}
		long[] tmult(long[] vec) {
			long[] res = new long[n];
			for(int i = 0; i < n; i++) {
				for(int j = 0; j < n; j++) {
					res[j] += vec[i] * mat[i][j] % mod;
					res[j] %= mod;
				}
			}
			return res;
		}
	}

}