Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers…
- User
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers. Input
The first line contains two integers n and k (1 ≤ n, k ≤ 109) — the number of elements in the permutation and the lexicographical number of the permutation.
Output
If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers.
Examples
Input
7 4
Output
1
Input
4 7
Output
1
Note
A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 ≤ i ≤ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 ≤ i ≤ n), that ai < bi, and for any j (1 ≤ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations.
In the first sample the permutation looks like that:
1 2 3 4 6 7 5
The only suitable position is 4.
In the second sample the permutation looks like that:
2 1 3 4
The only suitable position is 4.
Assistant
To solve this problem, we need to determine the k-th lexicographical permutation of numbers from 1 to n and count how many positions in this permutation are "lucky" both in terms of their index and the value at that index. A lucky number is defined as a number composed exclusively of the digits 4 and 7.
Approach
-
Check Validity of Permutation:
- First, determine the smallest integer ( m ) such that ( m! \geq k ). If ( m ) exceeds ( n ), the permutation does not exist, and we return -1.
-
Generate Lucky Numbers:
- Generate all lucky numbers up to ( n ). This can be efficiently done using a breadth-first search (BFS) approach starting from the digits 4 and 7, expanding by appending 4 or 7 to each number.
-
Determine Initial and Tail Segments:
- The first ( n - m ) elements of the permutation will be in their natural order. The remaining ( m ) elements form the tail segment which needs permutation.
-
Compute the Tail Permutation:
- Using the value ( k ), compute the ( (k-1) )-th lexicographical permutation (0-based) of the tail elements.
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.