Under construction

Still being built. Things may change

What makes 2022 special?

Interview

Time limit1sMemory limit1024 MB

Summary
Given N and base d, find the smallest number above N whose base-d digits are each of 0 to d-1 used exactly once.
Level

Easy3 of 10

Topics
Math, Brute force
Solved
No attempts yet

Problem

The date of the New Year contest is January 15, 2022. Junggyeom was happy that the contest was being held, and while staring at the title he noticed that 2022 is special in some way.

Yes. When 20222022 is written in base 55, it is 31042(5)31042_{(5)}, and each base-55 digit 00, 11, 22, 33, 44 appears exactly once. The next year with this property is 2054.

You are given a number NN and a base dd. Find the smallest number greater than NN such that, when written in base dd, each base-dd digit appears exactly once. Do not write leading zeros.

Input

The first line contains the number NN and the base dd, separated by a space, both written in base 1010.

Output

On the first line, print the smallest number greater than NN that, when written in base dd, contains each base-dd digit exactly once. Print it in base 1010.

If no such number exists, print −1-1 on the first line.

Constraints

  • 1≤N≤1091 \le N \le 10^9
  • 2≤d≤92 \le d \le 9
  • All input numbers are integers written in base 1010.

Hints

  • A positive integer AA written in base dd as anan−1⋯a1a0(d)a_n a_{n-1} \cdots a_1 a_0{}_{(d)} means A=an×dn+an−1×dn−1+⋯+a1×d1+a0×d0A = a_n \times d^n + a_{n-1} \times d^{n-1} + \cdots + a_1 \times d^1 + a_0 \times d^0, where an≠0a_n \neq 0.
    • For example, 2022=3×54+1×53+0×52+4×51+2×50=31042(5)2022 = 3 \times 5^4 + 1 \times 5^3 + 0 \times 5^2 + 4 \times 5^1 + 2 \times 5^0 = 31042_{(5)}.
  • Base-dd digits are integers from 00 up to but not including dd.
  • The base-dd representation of AA has each digit 0,1,⋯ ,d−10, 1, \cdots, d-1 exactly once when 0,1,⋯ ,d−10, 1, \cdots, d-1 each appear exactly once among an,an−1,⋯ ,a0a_n, a_{n-1}, \cdots, a_0.

Examples3

  1. Example 1

    Input
    2021 5
    
    Expected output
    2022
    
  2. Example 2

    Input
    2022 5
    
    Expected output
    2054
    
  3. Example 3

    Input
    13857 6
    
    Expected output
    14055