import Foundation
let main: () = {
    let PRIMS = Int.Prime.within(0 ..< 10000)
    var S = Set<Int>()
    var ans = 0
    var N = nextInt()
    while N != 1 && !N.isPrime {
        for p in PRIMS {
            var z = p
            while N.isMultiple(of: z) {
                    S.insert(z)
                    N = N / z
                    ans += 1
//print(z)
                    z *= p
            }
            if p > N { break }
        }
    }
    if N != 1 && !S.contains(N) { ans += 1}
    print(ans)
}()

//----------------------------------

let dx = [1, 0, -1, 0] //[1, 0, -1, 0, -1,  1, -1, 1]
let dy = [0, 1, 0, -1] //[0, 1, 0, -1, -1, -1,  1, 1]

@inlinable func gcd(_ a: Int, _ b: Int) -> Int { (b > 0) ? gcd(b, a % b) : a }
@inlinable func lcm(_ a: Int, _ b: Int) -> Int { a / gcd(a, b) * b }

//----------------------------------

infix operator  =~ : ComparisonPrecedence
infix operator !=~ : ComparisonPrecedence
func =~ <T: FixedWidthInteger>(left: T, right: Range<T>) -> Bool { right ~= left }
func !=~ <T: FixedWidthInteger>(left: T, right: Range<T>) -> Bool { !(right ~= left) }
func =~ <T: FixedWidthInteger>(left: T, right: ClosedRange<T>) -> Bool { right ~= left }
func !=~ <T: FixedWidthInteger>(left: T, right: ClosedRange<T>) -> Bool { !(right ~= left) }

func =~ <T: Collection > (left: T.Element, right: T) -> Bool where T.Element : Equatable { right.contains(left) }
func !=~ <T: Collection > (left: T.Element, right: T) -> Bool where T.Element : Equatable { !right.contains(left) }

infix operator /^ : MultiplicationPrecedence
infix operator /^= : AssignmentPrecedence
func /^ <T: FixedWidthInteger>(left: T, right: T) -> T { (left + (right - 1)) / right }
func /^= <T: FixedWidthInteger>(left: inout T, right: T) { left = (left + (right - 1)) / right }

@inlinable func chmax<T: Comparable>(_ m: inout T, _ q: T) { if (m < q) { m = q } }
@inlinable func chmin<T: Comparable>(_ m: inout T, _ q: T) { if (m > q) { m = q } }
@inlinable func chRmax<T: Comparable>(_ m: inout T, _ q: T) -> Bool { if (m < q) { m = q; return true } else { return false } }
@inlinable func chRmin<T: Comparable>(_ m: inout T, _ q: T) -> Bool { if (m > q) { m = q; return true } else { return false } }

prefix operator *
prefix func * <T> (a: [T]) -> (T, T) { (a[0], a[1]) }
prefix func * <T> (a: [T]) -> (T, T, T) { (a[0], a[1], a[2]) }
prefix func * <T> (a: [T]) -> (T, T, T, T) { (a[0], a[1], a[2], a[3]) }
prefix func * <T> (a: [T]) -> (T, T, T, T, T) { (a[0], a[1], a[2], a[3], a[4]) }
prefix func * <T> (a: [T]) -> (T, T, T, T, T, T) { (a[0], a[1], a[2], a[3], a[4], a[5]) }

func printErr(_ str: String, terminator: String = "\n") {
    let s = str + terminator
    FileHandle.standardError.write(s.data(using: .utf8)!)
    FileHandle.standardError.synchronizeFile()
}

@inlinable func next() -> String { readLine()! }
@inlinable func nextInt() -> Int { Int(next())! }
@inlinable func nextDouble() -> Double { Double(next())! }
@inlinable func listOfString() -> [String] { next().split(separator: " ").map(String.init) }
@inlinable func listOfInt() -> [Int] { listOfString().map { Int($0)! } }
@inlinable func listOfInt(_ offset: Int = 0) -> [Int] { listOfString().map { Int($0)! + offset } }
@inlinable func listOfInt(_ offsets: Int ...) -> [Int] { listOfString().enumerated().map { Int($0.element)! + offsets[$0.offset % offsets.count] } }
@inlinable func listOfDouble(_ offset: Double = 0.0) -> [Double] { listOfString().map { Double($0)! + offset } }
@inlinable func listOfDouble(_ offsets: Double ...) -> [Double] { listOfString().enumerated().map { Double($0.element)! + offsets[$0.offset % offsets.count] } }

extension Int {
    init(s: String) { self.init(s)! }
    var isEven: Bool { self.isMultiple(of: 2) }
    var isOdd: Bool { !self.isEven }
    var isTrue: Bool { self != 0 }
    var isFalse: Bool { !self.isTrue }
    var toString: String { String(self) }
    var toChar: Character { Character(UnicodeScalar(UInt8(self))) }
}
func + (left: Int, right: Bool) -> Int { left + (right ? 1 : 0) }
extension Character {
    var asciiCode: Int { Int(self.asciiValue!) }
    var string: String { String(self) }
}
extension String {
    @inlinable subscript (position: Int) -> Character { self[self.index(self.startIndex, offsetBy: position)] }
    @inlinable func repeate(_ times: Int) -> String { String(repeating: self, count: times) }
    //  @inlinable subscript (n: Int) -> String { String(self[self.index(self.startIndex, offsetBy: n)]) }
    //  @inlinable subscript (n: Int) -> Int { Int(self[self.index(self.startIndex, offsetBy: n)].asciiValue!) }
    var toInt: Int { Int(self)! }
}
extension String { // VB like
    @inlinable func _index(_ position: Int) -> String.Index! {
        if !(0 ..< self.count ~= position) { return nil }
        return self.index(self.startIndex, offsetBy: position)
    }
    @inlinable func mid(from index: Int, length: Int) -> String! {
        if let startPosition = self._index(index) {
            if let endPosition = self._index(index + length - 1) {
                return String(self[startPosition...endPosition])
            } else {
                let endPosition = self.index(before: self.endIndex)
                return String(self[startPosition...endPosition])
            }
        }
        return ""
    }
    @inlinable func left(_ length: Int) -> String { String(self.prefix(length)) }
    @inlinable func right(_ length: Int) -> String { String(self.suffix(length)) }
}

extension Dictionary {
    @inlinable mutating func getOrSet(_ key: Key, _ defaultValue: () -> Value) -> Value {
        if let stored = self[key] { return stored }
        else {
            let newValue = defaultValue()
            self[key] = newValue
            return newValue
        }
    }
    @inlinable mutating func getOrElse(_ key: Key, _ defaultValue: () -> Value) -> Value {
        if let stored = self[key] { return stored } else { return defaultValue() }
    }
    @inlinable func containsKey(_ key: Key) -> Bool { self.keys.contains(key) }
}

extension Set {
    static func += (left: inout Set<Element>, right: Element) { left.insert(right) }
    static func -= (left: inout Set<Element>, right: Element) { left.remove(right) }
}

extension Array {
    static func += (left: inout Array<Element>, right: Element) { left.append(right) }
    init(_ size: Int, _ initValue: ((Int) -> Element)) {
        self = [Element]()
        for index in 0 ..< size {
            let value = initValue(index)
            self.append(value)
        }
    }
    init(_ size: Int, _ initValue: (() -> Element)) {
        self = [Element]()
        for _ in 0 ..< size {
            let value = initValue()
            self.append(value)
        }
    }
}
typealias IntArray = Array<Int>
typealias DoubleArray = Array<Double>
typealias BoolArray = Array<Bool>
typealias StringArray = Array<String>

extension Array where Element == Int {
    init(_ size: Int) {
        self = [Element](repeating: 0, count: size)
    }
}
extension Array where Element == Double {
    init(_ size: Int) {
        self = [Element](repeating: 0.0, count: size)
    }
}
extension Array where Element == Bool {
    init(_ size: Int) {
        self = [Element](repeating: false, count: size)
    }
}
extension Array where Element == String {
    init(_ size: Int) {
        self = [Element](repeating: "", count: size)
    }
}

extension Array {
    @inlinable func count(_ predicate: ((Element) -> Bool)) -> Int {
        var cnt = 0; for e in self { if (predicate(e)) { cnt += 1 } }
        return cnt
    }
    @inlinable func groupBy<K>(_ keySelector: (Element) -> K) -> [K : [Element]] {
        var destination = [K : [Element]]()
        for element in self {
            let key = keySelector(element)
            var list = destination.getOrSet(key) { [Element]() }
            list.append(element)
            destination[key] = list
        }
        return destination
    }
    @inlinable func groupByIndexed<K>(_ keySelector: (Element) -> K) -> [K : [Int]] {
        var destination = [K : [Int]]()
        for element in self.enumerated() {
            let key = keySelector(element.element)
            var list = destination.getOrSet(key) { [Int]() }
            list.append(element.offset)
            destination[key] = list
        }
        return destination
    }
}

extension Array {
    func binarySearch(_ element: Element, by compare: (Element, Element) -> Int, fromIndex: Int = 0, toIndex: Int = -1) -> Int {
        var low = fromIndex
        var high = (toIndex == -1) ? self.count - 1 : toIndex - 1
        while (low <= high) {
            let mid = (low + high) >> 1 // safe from overflows
            let midVal = self[mid]
            let cmp = compare(midVal, element)
            if (cmp < 0) { low = mid + 1 }          //-1
            else if (0 < cmp) { high = mid - 1 }    // 1
            else { return mid } // key found        // 0
        }
        return -(low + 1)  // key not found
    }
}
extension Array where Element : Comparable {
    func binarySearch(_ element: Element, fromIndex: Int = 0, toIndex: Int = -1) -> Int {
        var low = fromIndex
        var high = (toIndex == -1) ? self.count - 1 : toIndex - 1
        while (low <= high) {
            let mid = (low + high) >> 1 // safe from overflows
            let midVal = self[mid]
            if (midVal < element) { low = mid + 1 }
            else if (midVal > element) { high = mid - 1 }
            else { return mid } // key found
        }
        return -(low + 1)  // key not found
    }
}

extension Array where Element == Int {
    @inlinable func distinct() -> [Element] {
        var set = Set<Element>(), ary = [Element]()
        for n in self.indices { if !set.contains(self[n]) { ary.append(self[n]); set.insert(self[n]) } }
        return ary
    }
    @inlinable func any(_ predicate: (Element) -> Bool) -> Bool {
        var any = false; for element in self { if predicate(element) { any = true } }
        return any
    }
    @inlinable func all(_ predicate: (Element) -> Bool) -> Bool {
        self.allSatisfy(predicate)
    }
    @inlinable func sum() -> Element { self.reduce(0, +) }
    @inlinable func sum(by predicate: (Element) -> Element) -> Element {
        var sum = 0; for e in self { sum += predicate(e) }
        return sum
    }
    @inlinable func joinToString(_ sepatator: String = " ") -> String { self.map { String($0) }.joined(separator: sepatator) }
}

extension Array where Element == Double {
    @inlinable func sum() -> Element { self.reduce(0.0, +) }
    @inlinable func sum(by predicate: (Element) -> Element) -> Element {
        var sum = 0.0; for e in self { sum += predicate(e) }
        return sum
    }
    @inlinable func joinToString(_ sepatator: String = " ") -> String { self.map { String($0) }.joined(separator: sepatator) }
}
extension Array where Element == String {
    @inlinable func toIntDouble() -> (Int, Double) { (Int(self[0])!, Double(self[1])!) }
    @inlinable func toIntString() -> (Int, String) { (Int(self[0])!, self[1]) }
    @inlinable func toIntIntString() -> (Int, Int, String) { (Int(self[0])!, Int(self[1])!, self[2]) }
}

@inlinable func block( _ action: () -> Void) {
    action()
}
@inlinable func repeate(_ times1: Int, _ action: () -> Void) {
    for _ in 0 ..< times1 { action() }
}
@inlinable func repeate(_ times1: Int, _ action: (Int) -> Void) {
    for index1 in 0 ..< times1 {
        action(index1)
    }
}
@inlinable func repeate(_ times1: Int, _ times2: Int, _ action: (Int, Int) -> Void) {
    for index1 in 0 ..< times1 {
        for index2 in 0 ..< times2 {
            action(index1, index2)
        }
    }
}
@inlinable func repeate(_ times1: Int, _ times2: Int, _ times3: Int, _ action: (Int, Int, Int) -> Void) {
    for index1 in 0 ..< times1 {
        for index2 in 0 ..< times2 {
            for index3 in 0 ..< times3 {
                action(index1, index2, index3)
            }
        }
    }
}
@inlinable func repeate(_ times1: Int, _ times2: Int, _ times3: Int, _ times4: Int, _ action: (Int, Int, Int, Int) -> Void) {
    for index1 in 0 ..< times1 {
        for index2 in 0 ..< times2 {
            for index3 in 0 ..< times3 {
                for index4 in 0 ..< times4 {
                    action(index1, index2, index3, index4)
                }
            }
        }
    }
}

func measureTimeSeconds(block: (() -> Void)) -> Double {
    let startTime = Date()
    block()
    let duration = -startTime.timeIntervalSinceNow
    return duration
}

public extension UInt64 {
    /// (x * y) mod m
    /// unlike naive x * y % m, this does not overflow.
    public static func mulmod(_ x:UInt64, _ y:UInt64, _ m:UInt64)->UInt64 {
        if (m == 0) { fatalError("modulo by zero") }
        if (m == 1) { return 1 }
        if (m == 2) { return x & 1 }  // just odd or even
        var a = x % m;
        if a == 0 { return 0 }
        var b = y % m;
        if b == 0 { return 0 }
        var r:UInt64 = 0;
        while a > 0 {
            if a & 1 == 1 { r = (r &+ b) % m }
            a >>= 1
            b = (b << 1) % m
        }
        return r
        // return c_mulmod(a, b, m)
    }
}
public extension UInt {
    /// (x * y) mod m without worring about overflow.
    public static func mulmod(_ x:UInt, _ y:UInt, _ m:UInt)->UInt {
        let (xy, overflow) = (x * y, false)  //.multiplyWithOverflow(x, y)
        return !overflow ?  xy % m : UInt(UInt64.mulmod(UInt64(x),UInt64(y),UInt64(m)))
    }
    /// (x ** y) mod m
    public static func powmod(_ x:UInt, _ y:UInt, _ m:UInt)->UInt {
        if (m == 0) { fatalError("modulo by zero") }
        if (m == 1) { return 1 }
        if (m == 2) { return x & 1 }  // just odd or even
        var r:UInt = 1, t = x, n = y
        while n > 0 {
            if n & 1 == 1 { r = mulmod(r, t, m) }
            t = mulmod(t, t, m)
            n >>= 1
        }
        return r
    }
    /// Greatest Common Divisor
    public static func gcd(_ m:UInt, _ n:UInt)->UInt {
        if n == 0 { return m }
        if m < n { return gcd(n, m) }
        let r = m % n
        return r == 0 ? n : gcd(n, r)
    }
    /// b ** x
    public static func ipow(_ b:UInt, _ x:UInt)->UInt {
        var r:UInt = 1, t = b, n = x
        while n > 0 {   // &* is neccessary to avoid overflow exception
            if n & 1 == 1 {
                r = r &* t
            }
            n >>= 1; t = t &* t
        }
        return r
    }
    /// Integer Square Root of `n`
    public static func isqrt(_ n:UInt)->UInt {
        var xk = UInt(sqrt(Double(n)))
        if xk <= 67108864 { return (xk)}  //sqrt(2^52)
        repeat {
            let xk1 = (xk + n / xk) / 2
            if xk1 >= xk { return xk }
            xk = xk1
        } while true
    }

    /// Integer Cube Root of `n`
    public static func icbrt(_ n:UInt)->UInt {
        if n == 0 { return 0 }
        if n == 1 { return 1 }
        if n == 18446744073709551615 { return 2642245 }
        var xk = n
        repeat {
            let xk1 = (2*xk + n/xk/xk) / 3
            if xk1 >= xk { return xk }
            xk = xk1
        } while true
    }
}
public extension Int {
    /// (x * y) mod m without worring about overflow.
    public static func mulmod(_ x:Int, _ y:Int, _ m:Int)->Int {
        let (ax, ay, am) = (abs(x),abs(y),abs(m))
        let sxy = 0 < x ? 0 < y ? 1 : -1 : 1
        return sxy * Int(UInt.mulmod(UInt(ax),UInt(ay),UInt(am)))
    }
    /// Greatest Common Divisor
    public static func gcd(_ m:Int, _ n:Int)->Int {
        if m < 0 {
            return gcd(-m, n < 0 ? -n : n)
        }
        if n == 0 { return m }
        if m < n { return gcd(n, m) }
        let r = m % n
        return r == 0 ? n : gcd(n, r)
    }
    /// b ** x
    public static func ipow(_ b:Int, _ n:Int)->Int {
        return Int(UInt.ipow(UInt(b), UInt(n)))
    }
    /// Integer Square Root of `n`
    public static func isqrt(_ n:Int)->Int {
        return Int(UInt.isqrt(UInt(n)))
    }
}
public extension UInt {
    class Prime {
        public init(){}
        public func generate()->AnyIterator<UInt> {
            var currPrime:UInt = 0
            return AnyIterator {
                let nextPrime = currPrime.nextPrime
                if nextPrime > currPrime {
                    currPrime = nextPrime;
                    return currPrime
                }
                return nil
            }
        }
    }
}
public extension UInt.Prime {
    /// primes less than 2048
    public static let tinyPrimes:[UInt] = {
        var ps:[UInt] = [2, 3]
        var n:UInt = 5
        while n < 2048 {
            for p in ps {
                if n % p == 0 { break }
                if p * p > n  { ps.append(n); break }
            }
            n += 2
        }
        return ps
    }()
    /// ### [A014233]
    ///
    /// Smallest odd number for which Miller-Rabin primality test
    /// on bases <= n-th prime does not reveal compositeness.
    ///
    /// [A014233]: https://oeis.org/A014233
    public static let A014233:[UInt] = [
        2047,                   // p0   = 2
        1373653,                // p1   = 3
        25326001,               // p2   = 5
        3215031751,             // p3   = 7
        2152302898747,          // p4   = 11
        3474749660383,          // p5   = 13
        341550071728321,        // p6   = 17
        341550071728321,        // p7   = 19
        3825123056546413051,    // p8   = 23
        3825123056546413051,    // p9   = 29
        3825123056546413051,    // p10  = 31
        0                       // p11  = 37; 318665857834031151167461  > UInt.max
    ]
    /// [Miller-Rabin] test `n` for `base`
    ///
    /// [Miller-Rabin]: https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test
    public class func millerRabinTest(_ n:UInt, base:UInt)->Bool {
        if n < 2      { return false }
        if n & 1 == 0 { return n == 2 }
        var d = n - 1
        while d & 1 == 0 { d >>= 1 }
        var t:UInt = d
        var y = UInt.powmod(base, t, n)
        while t != n-1 && y != 1 && y != n-1 {
            y = UInt.mulmod(y, y, n)
            t <<= 1
        }
        return y == n-1 || t & 1 == 1
    }
    public class func isPrime(_ n:UInt)->Bool {
        if n < 2      { return false }
        if n & 1 == 0 { return n == 2 }
        if n % 3 == 0 { return n == 3 }
        if n % 5 == 0 { return n == 5 }
        if n % 7 == 0 { return n == 7 }
        for i in 0..<A014233.count {
            // print("millerRabinTest(\(n), base:\(smallPrimes[i]))")
            if millerRabinTest(n, base:tinyPrimes[i]) == false { return false }
            if n < A014233[i] { break }
        }
        return true
    }
    public class func nextPrime(_ n:UInt)->UInt {
        if n < 2 { return 2 }
        var u = n
        u += u & 1 == 0 ? 1 : 2
        while !isPrime(u) { u += 2 }
        return u
    }
    public class func prevPrime(_ n:UInt)->UInt {
        if n < 2 { return 2 }
        var u = n
        u -= u & 1 == 0 ? 1 : 2
        while !isPrime(u) { u -= 2 }
        return u
    }
    public class func within(_ range:Range<UInt>)->[UInt] {
        var result = [UInt]()
        var p = range.startIndex
        if !p.isPrime { p = p.nextPrime }
        while p < range.endIndex {
            result.append(p)
            p = p.nextPrime
        }
        return result
    }
    /// Try to factor `n` by [Pollard's rho] algorithm
    ///
    /// [Pollard's rho]: https://en.wikipedia.org/wiki/Pollard%27s_rho_algorithm
    ///
    /// - parameter n: the number to factor
    /// - parameter l: the number of iterations
    /// - parameter c: seed
    public class func pollardsRho(_ n:UInt, _ l:UInt, _ c:UInt)->UInt {
        //return UInt(c_pbrho(UInt64(n), UInt64(l), Int32(c)))
        var x:UInt = 2, y:UInt = 2, j:UInt = 2
        for i in 1...l {
            x = UInt.mulmod(x, x, n)
            x += c
            let d  = UInt.gcd(x < y ? y - x : x - y, n);
            if (d != 1) {
                return d == n ? 1 : d
            }
            if (i % j == 0) {
                y = x
                j += j
            }
        }
        return 1
    }
    // cf.
    //   http://en.wikipedia.org/wiki/Shanks'_square_forms_factorization
    //   https://github.com/danaj/Math-Prime-Util/blob/master/factor.c
    static let squfofMultipliers:[UInt] = [
        1,      3,      5,      7,      11,
        3*5,    3*7,    3*11,   5*7,    5*11,
        7*11,   3*5*7,  3*5*11, 3*7*11, 5*7*11, 3*5*7*11
    ]
    /// Try to factor `n` by [SQUFOF] = Shanks' Square Forms Factorization
    ///
    /// [SQUFOF]: http://en.wikipedia.org/wiki/Shanks'_square_forms_factorization
    public class func squfof(_ n:UInt)->UInt {
        let ks = squfofMultipliers.filter{n < UInt(Int.max) / $0}.reversed()
        // print("ks=\(ks)")
        for k in ks {
//            if UInt.multiplyWithOverflow(n, k).overflow { continue }
            //let g = UInt(c_squfof(UInt64(n), UInt64(k)))
            let g = squfof_one(n, k)
            // print("squof(\(n),\(k)) == \(g)")
            if g != 1 { return g }
        }
        return 1
    }
    public class func squfof_one(_ n:UInt, _ k:UInt)->UInt {
        // print("n=\(n),k=\(k)")
        if n < 2      { return 1 }
        if n & 1 == 0 { return 2 }
        let rn = UInt.isqrt(n)
        if rn * rn == n { return rn }
        // if overflows just give up
        if n > UInt(Int.max) { return 1 }
        let kn = Int(k) &* Int(n)
        let rkn = Int.isqrt(kn)
        var p0 = rkn
        var q0 = 1
        var q1 = kn &- p0*p0
        var b0, b1, p1, q2 : Int
        for i in 0..<Int.isqrt(2 * rkn) {
            // print("Stage 1: p0=\(p0), q0=\(q0), q1=\(q1)")
            b1 = (rkn &+ p0) / q1
            p1 = b1 &* q1 &- p0
            q2 = q0 &+ b1 &* (p0 - p1)
            if i & 1 == 1 {
                let rq = Int.isqrt(q1)
                if rq * rq == q1 {
                    //  square root found; the algorithm cannot fail now.
                    b0 = (rkn &- p0) / rq
                    p0 = b0 &* rq &+ p0
                    q0 = rq
                    q1 = (kn &- p0*p0) / q0
                    while true {
                        // print("Stage 2: p0=\(p0), q0=\(q0), q1=\(q1)")
                        b1 = (rkn &+ p0) / q1
                        p1 = b1 &* q1 &- p0
                        q2 = q0 &+ b1 &* (p0 - p1)
                        if p0 == p1 {
                            return UInt.gcd(n, UInt(p1))
                        }
                        p0 = p1; q0 = q1; q1 = q2;
                    }
                }
            }
            p0 = p1; q0 = q1; q1 = q2
        }
        return 1
    }
    /// factor `u` and return prime facrors of it in array.
    ///
    /// axiom: `UInt.Prime.factor(u).reduce(1,*) == u` for any `u:UInt`
    ///
    /// It should succeed for all `u <= Int.max` but may fail for larger UInts.
    /// In which case `1` is prepended to the result so the axiom still holds.
    public class func factor(_ u:UInt)->[UInt] {
        var n = u
        if n < 2 { return [n] }
        if isPrime(n) { return [n] }
        var result = [UInt]()
        for p in tinyPrimes[0..<83] {
            while n % p == 0 { result.append(p); n /= p }
            if n == 1 { return result }
        }
        if isPrime(n) { return result + [n] }
        if n < UInt(tinyPrimes.last! * tinyPrimes.last!) {
            for p in tinyPrimes[83..<tinyPrimes.count] {
                while n % p == 0 { result.append(p); n /= p }
                if n == 1 { return result }
            }
            if n != 1 { result.append(n) }
            return result
        }
        if isPrime(n) { return result + [n] }
        let l = Swift.min(UInt.isqrt(n), 0x1_0000)
        var d = pollardsRho(n, l, 1)
        if d == 1 {
            d = squfof(n)
        }
        result += d != 1 ? factor(d) + factor(n/d) : [1, n]
        result.sort(by: <)
        return result
    }
}
public extension UInt {
    /// true iff `self` is prime
    public var isPrime:Bool { return Prime.isPrime(self) }
    /// the next prime number to `self`
    public var nextPrime:UInt { return Prime.nextPrime(self) }
    /// the previous prime number from `self`
    public var prevPrime:UInt { return Prime.prevPrime(self) }
    /// the prime factors of `self`
    ///
    /// axiom: `i.primeFactors.reduce(1,*) == i` for any `i:Int`
    ///
    /// for negative integers, `-1` is appended to keep axiom.
    public var primeFactors:[UInt] { return Prime.factor(self) }
}
public extension Int {
    /// true iff `self` is prime
    public var isPrime:Bool {
        return self < 2 ? false : UInt(self).isPrime
    }
    /// the next prime number to `self`
    public var nextPrime:Int { return Int(UInt(self).nextPrime) }
    /// the previous prime number from `self`
    public var prevPrime:Int { return Int(UInt(self).prevPrime) }
    /// the prime factors of `self`
    ///
    /// axiom: `u.primeFactors.reduce(1,*) == u` for any `u:UInt`
    ///
    /// It may fail for `u > UInt(Int.max)`.
    /// In which case `1` is prepended to the result.
    public var primeFactors:[Int] {
        var result = UInt(abs(self)).primeFactors.map{ Int($0) }
        if self < 0 { result += [-1] }
        return result
    }
}
public extension Int {
    public class Prime {
        public init(){}
        public func generate()->AnyIterator<Int> {
            var currPrime = 0
            return AnyIterator {
                if currPrime < 9223372036854775783 {
                    currPrime = currPrime.nextPrime
                    return currPrime
                }
                return nil
            }
        }
    }
}
public extension Int.Prime {
    public class func within(_ range:Range<Int>)->[Int] {
        let start = UInt(Swift.max(range.startIndex, 0))
        let end   = UInt(range.endIndex)
        return UInt.Prime.within(start..<end).map{ Int($0) }
    }
}


import * as fs from 'fs';

const readString = (() => {
  const input = fs.readFileSync(0).toString();
  const words = input.split(/[ \n]/);
  let i = 0;
  return () => words[i++] || '';
})();
const readInt = () => parseInt(readString(), 10);
const readBigInt = () => BigInt(readString());

const gcd = (a: bigint, b: bigint) => {
  const _gcd = (a: bigint, b: bigint): bigint => {
    const q = a % b;
    return q === 0n ? b : _gcd(b, q);
  };
  return a > b ? _gcd(a, b) : _gcd(b, a);
};

const MOD = 1000000007;
const MOD_BIGINT = BigInt(MOD);
class ModBigInt {
  constructor(public v: bigint) {}

  static of(n: number | bigint) {
    return new ModBigInt(ModBigInt.toBigInt(n));
  }

  static toBigInt(other: number | bigint | ModBigInt) {
    if (typeof other === 'bigint') return other;
    if (typeof other === 'number') return BigInt(other);
    return other.v;
  }

  clone = () => new ModBigInt(this.v);
  plus = (other: number | bigint | ModBigInt) => {
    this.v = (this.v + ModBigInt.toBigInt(other)) % MOD_BIGINT;
    return this;
  };
  minus = (other: number | bigint | ModBigInt) => {
    this.v = (this.v + MOD_BIGINT - ModBigInt.toBigInt(other)) % MOD_BIGINT;
    return this;
  };
  multiply = (other: number | bigint | ModBigInt) => {
    this.v = (this.v * ModBigInt.toBigInt(other)) % MOD_BIGINT;
    return this;
  };
  pow = (other: number) => {
    const v = mod(1);
    for (let i = 0; i < other; i++) v.multiply(this.v);
    return v;
  };
}

const mod = ModBigInt.of;

const abs = (a: bigint) => (a > 0n ? a : -a);

const count = (s: number) => {
  return Math.floor(Math.sqrt(2 * s + 0.25) - 0.5);
};

(function main() {
  let N = readInt();
  const s: { [p: number]: number } = {};
  for (let p = 2; p <= 1000000; p++) {
    while (N % p === 0) {
      N /= p;
      s[p] = s[p] || 0;
      s[p]++;
    }
    if (N === 1) break;
  }

  let result = 0;
  for (const p of Object.keys(s) as any) {
    result += count(s[p]);
  }
  if (N > 1) result += 1;
  console.log(result);
})();


class AtCoder {

  input;
  input_i;
  constructor() {
      // 入力系
      this.input = require('fs').readFileSync('/dev/stdin', 'utf8').split(/[\s]/);
      this.input_i = -1;
  }
  n() {
      this.input_i++;
      return Number(this.input[this.input_i]);
  }
  nn(n) {
      const a = [];
      for (let i = 0; i < n; i++) {
          a.push(this.n());
      }
      return a;
  }
  s() {
      this.input_i++;
      return String(this.input[this.input_i]);
  }
  ss(n) {
      const a = [];
      for (let i = 0; i < n; i++) {
          a.push(this.s());
      }
      return a;
  }
  // コンソール
  o(...a) {
      console.log(...a);
  }
  // Math
  abs(a) {
      return Math.abs(a);
  }
  min(...a) {
      return Math.min(...a);
  }
  max(...a) {
      return Math.max(...a);
  }
  floor(a) {
      return Math.floor(a);
  }
  ceil(a) {
      return Math.ceil(a);
  }
  round(a) {
      return Math.round(a);
  }
  // ソート
  asc(ar) {
      const t = [...ar];
      ar.sort((a, b) => { return a - b; });
  }
  desc(ar) {
      const t = [...ar];
      ar.sort((a, b) => { return b - a; });
  }
  // 自作
  gcd(...arr) {
      for (let i = 0; i < arr.length - 1; i++) {
          let [x, y] = [arr[i], arr[i + 1]];
          while (y) {
              [x, y] = [y, x % y];
          }
          arr[i + 1] = x;
      }
      return arr[arr.length - 1];
  }
  ;
  lcm(...arr) {
      for (let i = 0; i < arr.length - 1; i++) {
          let [x, y] = [arr[i], arr[i + 1]];
          while (y) {
              [x, y] = [y, x % y];
          }
          arr[i + 1] = arr[i] * arr[i + 1] / x;
      }
      return arr[arr.length - 1];
  }
  ;
  isPrime(n) {
      if (n < 2)
          return false;
      const suq = Math.sqrt(n);
      for (let i = 2; i <= suq; i++) {
          if (n % i == 0) {
              return false;
          }
      }
      return true;
  }
  ;
  deduplicate(a) {
      return Array.from(new Set(a));
  }
  ;
  f(roop, callback) {
      for (let i = 0; i < roop; i++) {
          callback(i);
      }
  }
  ;
  Yes() {
      console.log('Yes');
  }
  No() {
      console.log('No');
  }
  YES() {
      console.log('YES');
  }
  NO() {
      console.log('NO');
  }
}
const m = () => {
  function pf(n: number) {
      let ob:any = {};
      var init = 2;
      while (n !== 1) {
          var i = init;
          while (i < Number.MAX_SAFE_INTEGER) {
              if(i > 1000000) {
                ob[i] = 1;
                return ob
              }
              if (n % i == 0) {
                  if (!ob[i]) {
                      ob[i] = 1;
                  } else {
                      ob[i] = ob[i] + 1;
                  }
                  n = n / i;
                  break;
              }
              i = i + 1;
          }
          init = i;
      }
      return ob;
  }
  const o = new AtCoder();
  let n = o.n();
  if (n == 1) {
      return o.o(0);
  }
  if (o.isPrime(n)) {
      return o.o(1);
  }
  let ob = pf(n);
  let ans = 0;
  Object.keys(ob).forEach((key) => {
      let t = 1;
      while (ob[key] >= 0) {
          ob[key] -= t;
          t++;
          if (ob[key] >= 0)
              ans++;
      }
  });
  o.o(ans);
};
m();


import { readFileSync } from "fs";

const read = () =>
  readFileSync(0, "utf8")
    .split("\n")
    .map((line) => line.split(" "));

const primeFactorize = (target: bigint) => {
  let n = target;
  const res = new Map<bigint, bigint>();

  for (let i = 2n; i * i <= n; i++) {
    if (n % i !== 0n) {
      continue;
    }

    let ex = 0n;
    while (n % i === 0n) {
      ex += 1n;
      n /= i;
    }

    res.set(i, ex);
  }

  if (n !== 1n) {
    res.set(n, 1n);
  }

  return res;
};

const main = (input: string[][]) => {
  const N = BigInt(input[0][0]);

  const pf = primeFactorize(N);

  let answer = 0;

  pf.forEach((ex) => {
    let usedEx = 1;
    let usedCount = 0;

    while (usedEx <= ex) {
      usedCount += 1;
      usedEx += usedCount + 1;
    }

    answer += usedCount;
  });

  return answer;
};

console.log(main(read()));


import * as fs from 'fs'

function main(input: string[][]) {
  const N = Number(input[0][0])
  let n = N
  let count = 0
  for (let i = 2; i < N; i += 1) {
    let divisor = i
    while (n % divisor === 0) {
      count += 1
      n = n / divisor
      divisor = divisor * i
    }
    if (i > n) break
  }

  console.log(count)
  return
}

main(
  fs
    .readFileSync('/dev/stdin', 'utf8')
    .trim()
    .split('\n')
    .map((i) => i.split(' '))
)


class AtCoder {

  input;
  input_i;
  constructor() {
      // 入力系
      this.input = require('fs').readFileSync('/dev/stdin', 'utf8').split(/[\s]/);
      this.input_i = -1;
  }
  n() {
      this.input_i++;
      return Number(this.input[this.input_i]);
  }
  nn(n) {
      const a = [];
      for (let i = 0; i < n; i++) {
          a.push(this.n());
      }
      return a;
  }
  s() {
      this.input_i++;
      return String(this.input[this.input_i]);
  }
  ss(n) {
      const a = [];
      for (let i = 0; i < n; i++) {
          a.push(this.s());
      }
      return a;
  }
  // コンソール
  o(...a) {
      console.log(...a);
  }
  // Math
  abs(a) {
      return Math.abs(a);
  }
  min(...a) {
      return Math.min(...a);
  }
  max(...a) {
      return Math.max(...a);
  }
  floor(a) {
      return Math.floor(a);
  }
  ceil(a) {
      return Math.ceil(a);
  }
  round(a) {
      return Math.round(a);
  }
  // ソート
  asc(ar) {
      const t = [...ar];
      ar.sort((a, b) => { return a - b; });
  }
  desc(ar) {
      const t = [...ar];
      ar.sort((a, b) => { return b - a; });
  }
  // 自作
  gcd(...arr) {
      for (let i = 0; i < arr.length - 1; i++) {
          let [x, y] = [arr[i], arr[i + 1]];
          while (y) {
              [x, y] = [y, x % y];
          }
          arr[i + 1] = x;
      }
      return arr[arr.length - 1];
  }
  ;
  lcm(...arr) {
      for (let i = 0; i < arr.length - 1; i++) {
          let [x, y] = [arr[i], arr[i + 1]];
          while (y) {
              [x, y] = [y, x % y];
          }
          arr[i + 1] = arr[i] * arr[i + 1] / x;
      }
      return arr[arr.length - 1];
  }
  ;
  isPrime(n) {
      if (n < 2)
          return false;
      const suq = Math.sqrt(n);
      for (let i = 2; i <= suq; i++) {
          if (n % i == 0) {
              return false;
          }
      }
      return true;
  }
  ;
  deduplicate(a) {
      return Array.from(new Set(a));
  }
  ;
  f(roop, callback) {
      for (let i = 0; i < roop; i++) {
          callback(i);
      }
  }
  ;
  Yes() {
      console.log('Yes');
  }
  No() {
      console.log('No');
  }
  YES() {
      console.log('YES');
  }
  NO() {
      console.log('NO');
  }
}
const m = () => {
  function pf(n: number) {
      let ob:any = {};
      var init = 2;
      while (n !== 1) {
          var i = init;
          while (i < Number.MAX_SAFE_INTEGER) {
              if(i > 1000000) {
                ob[i] = 1;
                return ob
              }
              if (n % i == 0) {
                  if (!ob[i]) {
                      ob[i] = 1;
                      break;
                  }
                  else {
                      ob[i] = ob[i] + 1;
                  }
                  n = n / i;
                  break;
              }
              i = i + 1;
          }
          init = i;
      }
      return ob;
  }
  const o = new AtCoder();
  let n = o.n();
  if (n == 1) {
      return o.o(0);
  }
  if (o.isPrime(n)) {
      return o.o(1);
  }
  let ob = pf(n);
  let ans = 0;
  Object.keys(ob).forEach((key) => {
      let t = 1;
      while (ob[key] >= 0) {
          ob[key] -= t;
          t++;
          if (ob[key] >= 0)
              ans++;
      }
  });
  o.o(ans);
};
m();


class AtCoder {
  constructor() {
      // 入力系
      this.input = require('fs').readFileSync('/dev/stdin', 'utf8').split(/[\s]/);
      this.input_i = -1;
  }
  n() {
      this.input_i++;
      return Number(this.input[this.input_i]);
  }
  nn(n) {
      const a = [];
      for (let i = 0; i < n; i++) {
          a.push(this.n());
      }
      return a;
  }
  s() {
      this.input_i++;
      return String(this.input[this.input_i]);
  }
  ss(n) {
      const a = [];
      for (let i = 0; i < n; i++) {
          a.push(this.s());
      }
      return a;
  }
  // コンソール
  o(...a) {
      console.log(...a);
  }
  // Math
  abs(a) {
      return Math.abs(a);
  }
  min(...a) {
      return Math.min(...a);
  }
  max(...a) {
      return Math.max(...a);
  }
  floor(a) {
      return Math.floor(a);
  }
  ceil(a) {
      return Math.ceil(a);
  }
  round(a) {
      return Math.round(a);
  }
  // ソート
  asc(ar) {
      const t = [...ar];
      ar.sort((a, b) => { return a - b; });
  }
  desc(ar) {
      const t = [...ar];
      ar.sort((a, b) => { return b - a; });
  }
  // 自作
  gcd(...arr) {
      for (let i = 0; i < arr.length - 1; i++) {
          let [x, y] = [arr[i], arr[i + 1]];
          while (y) {
              [x, y] = [y, x % y];
          }
          arr[i + 1] = x;
      }
      return arr[arr.length - 1];
  }
  ;
  lcm(...arr) {
      for (let i = 0; i < arr.length - 1; i++) {
          let [x, y] = [arr[i], arr[i + 1]];
          while (y) {
              [x, y] = [y, x % y];
          }
          arr[i + 1] = arr[i] * arr[i + 1] / x;
      }
      return arr[arr.length - 1];
  }
  ;
  isPrime(n) {
      if (n < 2)
          return false;
      const suq = Math.sqrt(n);
      for (let i = 2; i <= suq; i++) {
          if (n % i == 0) {
              return false;
          }
      }
      return true;
  }
  ;
  deduplicate(a) {
      return Array.from(new Set(a));
  }
  ;
  f(roop, callback) {
      for (let i = 0; i < roop; i++) {
          callback(i);
      }
  }
  ;
  Yes() {
      console.log('Yes');
  }
  No() {
      console.log('No');
  }
  YES() {
      console.log('YES');
  }
  NO() {
      console.log('NO');
  }
}
const m = () => {
  function pf(n) {
      let ob = {};
      var init = 2;
      while (n !== 1) {
          var i = init;
          while (i < Number.MAX_SAFE_INTEGER) {
              if (n % i == 0 || i > 1000000) {
                  if (!ob[i]) {
                      ob[i] = 1;
                  }
                  else {
                      ob[i] = ob[i] + 1;
                  }
                  n = n / i;
                  break;
              }
              i = i + 1;
          }
          init = i;
      }
      return ob;
  }
  const o = new AtCoder();
  let n = o.n();
  if (n == 1) {
      return o.o(0);
  }
  if (o.isPrime(n)) {
      return o.o(1);
  }
  let ob = pf(n);
  let ans = 0;
  Object.keys(ob).forEach((key) => {
      let t = 1;
      while (ob[key] >= 0) {
          ob[key] -= t;
          t++;
          if (ob[key] >= 0)
              ans++;
      }
  });
  o.o(ans);
};
m();


N,K=input().split()
nums = input().split()
cand = list(map(str,list(x for x in range(10))))
for num in nums:
  if num in cand:
    cand.remove(num)
work = []
if int(N) <= int(cand[-1]*len(N)):
  for i in range(len(N)):
    for c in cand:
      if int(N[i]) == int(c):
        work.append(c)
        break
      elif int(N[i]) < int(c):
        work.append(c)
        for j in range(i+1,len(N)):
          work.append(cand[0])
        print(''.join(work))
        exit()
else:
  if cand[0] != '0':
    work.append(cand[0])
  else:
    work.append(cand[1])
  for i in range(len(N)):
    work.append(cand[0])
print(''.join(work))


n,k=map(int,input().split())
d=list(map(int,input().split()))

num=[]
for i in range(10):
    if i not in d:
        num.append(i)
#print(num)
num.sort()
digit=len(str(n))
ns=str(n)

ans=''
cnt=0
while cnt<digit:

    for i in num:
        if int(ns[cnt])>i:continue
        if int(ns[cnt])==i:
            ans+=str(i)
            break
        else:
            ans+=str(i)+(digit-cnt-1)*str(num[0])
            cnt=digit
            break
    else:
        ans=str(num[0]) if num[0]!=0 else str(num[1])
        ans+=str(num[0])*digit
        cnt=digit
    cnt+=1
print(ans)


import math

total = list(map(lambda x: int(x), input().split()))
possible = list({0,1,2,3,4,5,6,7,8,9} - set(list(map(lambda x: int(x), input().split()))))
yen = [int(d) for d in str(total[0])]

i = 0
if yen[0] == 9 and 9 not in possible:
    zeros = [0] * len(yen)
    yen = [1] + zeros
    print(int(''.join(map(str, yen))))

while i < len(yen):
    if yen[i] not in possible:
        if yen[i] == 9 and i != 0:
            yen[i - 1] += 1
            for i in range(i, len(yen)):
                yen[i] = 0
        elif yen[i] != 9:
            for j in possible:
                if j > i:
                    yen[i] = j
    i = i + 1

print(int(''.join(map(str, yen))))


import java.util.*;
import java.io.*;
class Main {
    public static void main(String[] args) throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());

        int N = Integer.parseInt(st.nextToken());
        int K = Integer.parseInt(st.nextToken());

        boolean[] dislike = new boolean[10];
        st = new StringTokenizer(br.readLine());

        for(int i=0; i<K; i++){
            int d = Integer.parseInt(st.nextToken());
            dislike[d]=true;
        }

        int ans = 0;
        String n = Integer.toString(N);
        boolean inc=false;
        boolean raised=false;
        for(int i=0; i<n.length(); i++){
            int cur = n.charAt(i)-'0';
            int k=cur;
            if(raised)
                k=0;
            while(k<10){
                if(!dislike[k]){
                    ans=ans*10+k;
                    break;
                }
                k++;
            }
            if(k!=cur)
                raised=true;
            if(k==10){
                inc=true;
                k=0;
                while(k<10){
                    if(!dislike[k]){
                        ans=ans*10+k;
                        break;
                    }
                    k++;
                }
            }
        }
        if(inc){
            int k=0;
            while(k<10){
                if(!dislike[k]){
                    ans=ans*10+k;
                    break;
                }
                k++;
            }
        }
        System.out.println(ans);

    }
}


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

public class Main {
  static int MOD = 1000000007;
  static double EPS = 1e-9;

  public static void main(String[] args) throws IOException {
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

    StringTokenizer st = new StringTokenizer(in.readLine());

    String N = st.nextToken();
    int length = N.length();
    int K = Integer.parseInt(st.nextToken());

    TreeSet<Integer> set = new TreeSet<Integer>();

    st = new StringTokenizer(in.readLine());

    for (int i = 0; i < K; i++) {
      set.add(Integer.parseInt(st.nextToken()));
    }

    int[] valid = new int[10 - K];
    int index = 0;

    for (int i = 0; i < 10; i++) {
      if (!set.contains(i)) {
        valid[index] = i;
        index++;
      }
    }

    // System.out.println(Arrays.toString(valid));

    int res = 0;
    /*int max = -1;

    for (int i = 0; i < length; i++) {
      max = Math.max(max, N.charAt(i) - '0');
    }

    if (max > valid[valid.length - 1]) {
      res = valid[]
    } */

    boolean b = true;
    boolean large = false;

    for (int i = 0; i < length; i++) {
      int d = N.charAt(i) - '0';
      // System.out.println(d);
      boolean done = false;
      if (large) {
        res = res * 10 + valid[0];
        continue;
      }
      for (int j = 0; j < valid.length; j++) {
        if (valid[j] >= d) {
          if (i == 0 && valid[j] > d)
            large = true;
          res = res * 10 + valid[j];
          done = true;
          break;
        }
      }
      if (!done) {
        b = false;
        break;
      }
    }

    if (!b) {
      if (valid[0] == 0)
        res = valid[1];
      else
        res = valid[0];
      for (int i = 0; i < length; i++) {
        res = res * 10 + valid[0];
      }
    }

    System.out.println(res);

    in.close();
  }
}


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

public class Main {
	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer(br.readLine());
		int n = Integer.parseInt(st.nextToken());
		int k = Integer.parseInt(st.nextToken());
		boolean[] bad = new boolean[10];
		st = new StringTokenizer(br.readLine());
		for (int i = 0; i < k; i++) {
			int d = Integer.parseInt(st.nextToken());
			bad[d] = true;
		}
		for (int x = n; ; x++) {
			boolean yes = true;
			for (int y = x; y > 0; y /= 10) {
				int d = y % 10;
				if (bad[d]) {
					yes = false;
					break;
				}
			}
			if (yes) {
				System.out.println(x);
				return;
			}
		}
	}
}


import java.io.BufferedReader;

import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.TreeSet;

public class Main {
	public static int convertTo (ArrayList<Integer> a) {
		int result = 0 ;
		for(int i = a.size()-1; i >= 0 ; i --) {
			result += (int)(a.get(i)*(Math.pow(10,i)));
		}
		return result ;
	}
	public static void main(String[]args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String[] a = br.readLine().split(" ");
        int N = Integer.parseInt(a[0]);
        int r = N ;
        int K = Integer.parseInt(a[1]);
        HashSet<Integer> kNumbers = new HashSet<>();
        TreeSet<Integer> nNumbers = new TreeSet<>();
        String[] b = br.readLine().split(" ");
        for(int i = 0 ; i < K ; i ++) {
        	kNumbers.add(Integer.parseInt(b[i]));
        }
        for(int i = 0 ; i <= 9 ; i ++) {
        	if(!kNumbers.contains(i)) {
        		nNumbers.add(i);
        	}
        }
        ArrayList<Integer> number = new ArrayList<Integer>();
        while(N!= 0) {
        	 number.add(N%10);
        	  N/=10;
        }

        while(true) {
        	int c = 0 ;
        	for(int i = 0 ; i < number.size() ; i++) {
        		if(kNumbers.contains(number.get(i))) {
        			if(nNumbers.ceiling(number.get(i)) == null) {
        				number.set(i,nNumbers.floor(number.get(i)));
        				System.out.print(number.get(i));
        			}
        			else
        				number.set(i,nNumbers.ceiling(number.get(i)));
        		}
        		else {
        			c++ ;
        		}
        	}
        	if(c == number.size() && convertTo(number) >= r) {
        		System.out.print(convertTo(number));
        		break;
        	}
	}
	}
}


import java.util.*;
public class Main{

  public static void main(String[] args) {
   Scanner no=new Scanner(System.in);
   StringBuilder sb=new StringBuilder();
   int n=no.nextInt();
   int m=no.nextInt();
   int min=0;
   int arr[]=new int[10];
   for(int i=0;i<m;i++){
     arr[no.nextInt()]++;
   }
   int j=n;
   int u=j;
   for(j=n;j<10000;j++){
    //System.out.println(j);
    u=j;
     while(u!=0){
       if(arr[u%10]>0){
         break;
       }
       else{
         //System.out.println("h");
         u=u/10;
       }
     }
     if(u==0){
       break;
     }
   }
   if(u==0){
     System.out.println(j);
   }
  }

}


#include <bits/stdc++.h>
#define rep(i, z, n) for(int i = z; i < n; i++)
#define all(v) v.begin(), v.end()
typedef long long ll;
//const int INF = 1<<29;
//const int MODINF = 1000000007;
using namespace std;

int main(){
    string N;
    int K;
    cin >> N >> K;
    set<int> D;
    rep(i, 0, K) {
        int x;
        cin >> x;
        D.insert(x);
    }
    int mini = 0, mini2 = 1;
    rep(i, 0, 10){
        if (D.count(mini)){
            mini++;
        }
        else{
            break;
        }
    }
    rep(i, 0, 10){
        if (D.count(mini2)){
            mini2++;
        }
        else{
            break;
        }
    }

    int m = N.size();
    vector<int> n(m + 1, 0);
    rep(i, 1, m + 1){
        n.at(i) = N.at(i - 1) - '0';
    }
    bool can = false;

    rep(i, 1, m + 1){
        if(D.count(n.at(i))){
            while(D.count(n.at(i))){
                SKIP:
                n.at(i)++;
                if (n.at(i) == 10){
                    n.at(i) = mini;
                    n.at(i - 1)++;
                    if (D.count(n.at(i - 1))){
                        i--;
                        goto SKIP;
                    }
                }
            }
            rep(j, i + 1, m + 1){
                n.at(j) = mini;
            }
            break;
        }
    }
    SKIP1:
    if (n.at(0) != 0){
        cout << mini2;
    }
    rep(i, 1, m + 1){
        cout << n.at(i);
    }
    cout << endl;
}


#include <bits/stdc++.h>

#define ll long long
#define mk make_pair
#define pb push_back
#define ff first
#define sc second
#define all(x) x.begin(), x.end()

ll gcd(ll a, ll b){
   if(b == 0) return a;

   return gcd(b, a % b);
}

ll sum(int n){
   if(n == 0){
      return n;
   }else{
      return sum(n/10) + n%10;
   }
}
using namespace std;

int disl[10] = {1,1,1,1,1,1,1,1,1,1};//1's like 0's dislike
bool verify(int n){
   while(n > 0){
      if(disl[n%10] == 0) return false;
      n/=10;
   }
   return true;
}

int main(){

   ios_base::sync_with_stdio(0);
   cin.tie(0);
   cout.tie(0);

   int n; cin >> n;
   int k; cin >> k;
   while(k--){
      int dint; cin >> dint;
      disl[dint] = 0;
   }

   for(int i = n; ; i++){
      if(verify(i)){
         cout << i; break;
      }
   }
   return 0;
}


#include <bits/stdc++.h>
#include <vector>
#include <iostream>
#include<algorithm>
#include<string>
#include <map>
#include <queue>
#include <stack>
#include <set>

#define DIV 1000000007
using namespace std;
using ll = long long;

int main() {
	int N, K;
	cin >> N >> K;

	vector<bool> deg(10, true);
	for (int i = 0; i < K; i++) {
		int d;
		cin >> d;
		deg[d] = false;
	}

	int ans;
	bool flag = false;
	for (ans = N; !flag; ans++) {
		int temp = ans;
		flag = true;
		while (temp > 0) {
			if (!deg[temp % 10]) {
				flag = false;
				break;
			}
			temp /= 10;
		}
	}

	cout << ans-1 << endl;
}


#include <bits/stdc++.h>
using namespace std;
#define M 1000000007
long long int power(int a,int b)
{
    if(b==0)
        return 1;
    long long int k=power(a,b/2);
    if(b%2==0)
        return ((k%M)*(k%M))%M;
    else
        return ((k%M)*(k%M)*(a%M))%M;
}
long long int fact(long long int n)
{
    if(n==1 || n==0)
        return 1;
    else
        return ((n%M)*(fact(n-1)%M))%M;

}
int div(int n)
{  int c=0;
    for(int i=1;i<=sqrt(n);i++)
    {
        if(n%i==0)
        {
          if(n/i==i)
            c++;
          else
            c+=2;
        }

    }

    return  c;
}
int func(int n)
{
    return (n*(n+1))/2;
}
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
     #ifndef ONLINE_JUDGE

    freopen("input.txt","r",stdin);
    freopen("output.txt","w",stdout);

   #endif

        string str;
        cin>>str;
        int n;
        cin>>n;
        bool arr[10];
        memset(arr,1,sizeof(arr));
        for(int i=0;i<n;i++)
        {
            int h;
            cin>>h;
            arr[h]=0;
        }
        for(int i=0;i<str.length();i++)
        {

            for(int j=0;j<=9;j++)
            {
                if(arr[j]==1 && (str[i]-48)<=j)
                {
                    str[i]=char(48+j);
                    break;
                }
            }
        }
       cout<<str;

 return 0;
}


#include<bits/stdc++.h>
using namespace std;
#define fori(x,y)   for(ll i=x;i<y;i++)
#define forj(x,y)   for(ll j=x;j<y;j++)
#define rfori(a,b)   for(int i=a;i>=b;i--)
#define for_it(a)     for(auto it: a)
#define pb          push_back
#define pf          push_front
#define ff          first
#define ss          second
#define all(x)      x.begin(),x.end()
#define mp          make_pair
#define mod         1000000007
#define mem(a,b)    memset(a,b,sizeof(a))
#define ld          long double
#define endl        "\n"
#define ll          long long
#define llu         unsigned long long
#define pii         pair<int,int>
#define pll         pair<ll,ll>
#define vl          vector<ll>
#define vi          vector<int>
#define vc          vector<char>
#define vs          vector<string>
#define si          set<int>
#define spii        set<pii>
#define usi         unordered_set<int>
#define usl         unordered_set<ll>
#define uspii       unordered_set<pii>
#define mii         map<int,int>
#define umii        unordered_map<int,int>
#define pqmx        priority_queue<int>
#define pqmn        priority_queue<int,vi,greater<int>>
#define setbits(x)  __builtin_popcountll(x)
#define fast        ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define testcase    int test;cin>>test;for(ll tst=0;tst<test;tst++)
int xx[4]={0,0,1,-1};
int yy[4]={-1,1,0,0};

/*-----------------------------------------------------------------------------------------------------------------*/

int main()
{
	#ifndef ONLINE_JUDGE
	freopen("C_IN.txt","r",stdin);
	freopen("C_Out.txt","w",stdout);
	#endif
	fast;

	ll n,m;
	cin>>n>>m;
	vl v(10,0);
	fori(0,m)
	{
		int x;
		cin>>x;
		v[x]++;
	}
	ll res=0,b=1;
	while(n)
	{
		int rem=n%10;
		if(v[rem])
		{
			rem++;
		}
		res+=rem*b;
		b*=10;
		n=n/10;
	}
	cout<<res<<endl;
	return 0;
}


#include<bits/stdc++.h>
using namespace std;
#define fori(x,y)   for(ll i=x;i<y;i++)
#define forj(x,y)   for(ll j=x;j<y;j++)
#define rfori(a,b)   for(int i=a;i>=b;i--)
#define for_it(a)     for(auto it: a)
#define pb          push_back
#define pf          push_front
#define ff          first
#define ss          second
#define all(x)      x.begin(),x.end()
#define mp          make_pair
#define mod         1000000007
#define mem(a,b)    memset(a,b,sizeof(a))
#define ld          long double
#define endl        "\n"
#define ll          long long
#define llu         unsigned long long
#define pii         pair<int,int>
#define pll         pair<ll,ll>
#define vl          vector<ll>
#define vi          vector<int>
#define vc          vector<char>
#define vs          vector<string>
#define si          set<int>
#define spii        set<pii>
#define usi         unordered_set<int>
#define usl         unordered_set<ll>
#define uspii       unordered_set<pii>
#define mii         map<int,int>
#define umii        unordered_map<int,int>
#define pqmx        priority_queue<int>
#define pqmn        priority_queue<int,vi,greater<int>>
#define setbits(x)  __builtin_popcountll(x)
#define fast        ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define testcase    int test;cin>>test;for(ll tst=0;tst<test;tst++)
int xx[4]={0,0,1,-1};
int yy[4]={-1,1,0,0};

/*-----------------------------------------------------------------------------------------------------------------*/

int main()
{
	#ifndef ONLINE_JUDGE
	freopen("C_IN.txt","r",stdin);
	freopen("C_Out.txt","w",stdout);
	#endif
	fast;

	ll n,m;
	cin>>n>>m;
	vl v(10,0);
	fori(0,m)
	{
		int x;
		cin>>x;
		v[x]++;
	}
	int res=0,b=1;
	while(n)
	{
		int rem=n%10;
		if(v[rem])
		{
			rem++;
		}
		res+=rem*b;
		b*=10;
		n=n/10;
	}
	cout<<res<<endl;
	return 0;
}


#include <stdio.h>
#include <stdbool.h>

int n;  /* 商品の金額 */
int k;  /* 嫌いな数字の個数を指定 */
int k_array[10]; /* 嫌いな数を指定する */

bool num_chcek(int n){
    while(n > 0){   /* 0より大きい間ループ */
        for(int i = 0; i < k; i++){
            if(n%10 == k_array[i]){ /* n/10の剰余 */
                return false;   /* 0 */
            }
        }
        n /= 10;   /* 桁ずらし */
    }
    return true;    /* 1 */
}

int main(){
    scanf("%d%d",&n,&k);
    for(int i = 0;i < k; i++){
        scanf("%d",&k_array[i]);
    }

    for(int i = n;;i++){
        if(num_chcek(i)){   /* trueなら出力 */
            printf("%d\n",i);
            break;
        }
    }
}


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#define MOD1 1000000007
#define MOD2 998244353
#define LIMIT1 200002
#define LIMIT2 500002
typedef long long ll;
typedef long double ld;
typedef const void cv;
#define rep(i,n) for((i)=0;(i)<(n);(i)++)
#define per(i,n) for((i)=(n)-1;(i)>=0;(i)--)
#define max(a,b) ((a)>(b) ? (a) : (b))
#define min(a,b) ((a)<(b) ? (a) : (b))
#define zt(a,b) (max((a),(b))-min((a),(b)))
#define absl(v) labs((v))
ll gcd(ll a,ll b){return b?gcd(b,a%b):a;}
ll nPr(int n,int r){ll i,result=1;rep(i,r){result*=(ll)(n-i);}return result;}
ll nCr(int n,int r){ll i,result=1;if(n<r) return 0;rep(i,min(r,n-r)){result*=(ll)(n-i);result/=(ll)(i+1);}return result;}
#define nHr(n,r) nCr((int)((n)+(r)+1),(int)(r))
#define sankaku(x) (((x)*((x)+1))/2)
int dx[8]={1,0,-1,0,1,-1,-1,1},dy[8]={0,1,0,-1,1,1,-1,-1};
int upint(cv *a, cv *b) { return *(int *)a < *(int *)b ? -1 : *(int *)a > *(int *)b ? 1 : 0; }
int downint(cv *a, cv *b) { return *(int *)a < *(int *)b ? 1 : *(int *)a > *(int *)b ? -1 : 0; }
int upchar(cv *left, cv *right) {return strcmp((char *)left,(char *)right);}
int downchar(cv *left, cv *right) {return strcmp((char *)right,(char *)left);}
void tmpInit(int *c,ll m) {ll i;rep(i,m) c[i]=i;}
ll modpow(ll a, ll n, ll mod) {
  ll res = 1;
  while (n > 0) {
    if (n & 1){
      res *= a; if(mod>=1) res %= mod;
    }
    a *= a; if(mod>=1) a %= mod;
    n >>= 1;
  }
  return res;
}
void initialize(){

}
int a[LIMIT2]={0};
ll k;
int find(ll price){
  ll i,j;
  j=price%10;
  if(price<=0) return 1;
  rep(i,k) if(a[i]==j) return 0;
  return find(price/10);
}
int main(void){
  initialize();
  ll n,m,i,j,result=0;
  char s[LIMIT1];

  scanf("%lld %lld",&n,&k);
  rep(i,k) scanf("%d",&a[i]);
  i=n;
  while(1){
    if(find(i)==1){
      result = i;
      break;
    }
    i++;
  }
  printf("%lld\n",result);
  return 0;
}


#include <stdio.h>

int search(int n,int k,int *hate){
  int i;
  for(i=0;i<k;i++){
    if(n==hate[i]){
      return 1;
    }
  }
  return 0;
}

int main(){
  int hate[9];
  int n,k,i,ok=0,tmp;

  scanf("%d %d",&n,&k);
  for(i=0;i<k;i++){
    scanf("%d",&hate[i]);
  }

  while(ok==0){
    ok=1;
    tmp=n;
    while(0<tmp){
      if(search(tmp%10,k,hate)==1){
        ok=0;
        n++;
        break;
      }
      tmp=tmp/10;
    }
  }

  printf("%d",n);
}


#include <stdio.h>
#include <stdbool.h>

int banum[10];
bool judge (int N,int K) {
    while (N > 0) {
        for (int i = 0; i < K; i++) {
            if (N % 10 == banum[i])
                return false;
        }
        N /= 10;
    }
    return true;
}

int main(void)
{
   int N, K;
    scanf("%d %d", &N, &K);
    for (int i = 0; i < K; i++)
        scanf("%d", &banum[i]);
    for (int i = N;; i++) {
        if (judge(N, K)) {
            printf("%d", N);
            return 0;
        }
    }
}


#include <stdio.h>
#include <stdbool.h>

int banum[10];
bool judge (int N,int K) {
    while (N > 0) {
        for (int i = 0; i < K; i++) {
            if (N % 10 == banum[i])
                return false;
        }
        N /= 10;
    }
    return true;
}

int main(void)
{
   int N, K;
    scanf("%d %d", &N, &K);
    for (int i = 0; i < K; i++)
        scanf("%d", &banum[i]);
    for (int i = N;; i++) {
        if (judge(N, K)) {
            printf("%d", N);
            break;
        }
    }
    return 0;
}


#include<stdio.h>
int main()
{
    int n,k,i,j,s=0,t,m=0,p=0,q=0,e,u,v;
    scanf("%d%d",&n,&k);
    int pt[k],pl[10],po[10];
    for(i=0;i<k;i++)
    {
        scanf("%d",&pt[i]);
    }
    for(i=0;i<=9;i++)
    {
        for(j=0;j<k;j++)
       {
           if(i==pt[j])
           {
               p=1;
               break;
           }
       }
       if(p==0)
       {
           po[q] = i;
           q++;
       }
       else
       {
           p = 0;
           continue;
       }
   }
    for(i=0;i<=q;i++)
    {
        for(j=i+1;j<q;j++)
        {
            if(po[i]>po[j])
            {
                e = po[i];
                po[i] = po[j];
                po[j] = e;
            }
        }
    }
    for(i=0;n!=0;i++)
    {
        pl[i] = n%10;
        for(j=0;j<k;j++)
        {
            u = n/10;
            if(pl[i]==pt[j] && u!=0)
            {
                pl[i] = po[0];
                break;
            }
            if(pl[i]==pt[j] && u==0)
            {
                pl[i] = pl[i] +1;
                j = -1;
            }
        }
        n = n/10;
        m++;
    }
    for(i=m-1;i>=0;i--)
    {
        printf("%d",pl[i]);
    }
    return 0;
}


'use strict'

const main = (INPUT) => {
  const input = INPUT.split('\n')
  const N = input[0].split(' ')[0].split('').map(n => Number(n)).reverse()
  const D = input[1].split(' ').map(n => Number(n))
  const ary = []
  for (let i = 0; i <= 9; i++) {
    if (D.indexOf(i) == -1) {
      ary.push(i)
    }
  }
  let flag
  for (let i = 0; i < N.length; i++) {
    while (true) {
      if (ary.indexOf(N[i]) >= 0) {
        if (flag && i == N.length - 1) {
          for (let j = 0; j < i; j++) {
            N[j] = ary[0]
          }
          i = 0
          flag = false
          continue
        }
        break
      }
      N[i] = N[i] + 1
      flag = true
      if (N[i] >= 10) {
        if (i == N.length - 1) {
          N.push(1)
          N[i] = 0
        } else {
          N[i + 1] = N[i + 1] + 1
          N[i] = 0
        }
      }
    }
  }

  console.log(N.reverse().join(''))
}

main(require('fs').readFileSync('/dev/stdin', 'utf8'))


'use strict;'
function main() {
  const input = require("fs").readFileSync("/dev/stdin", "utf-8").trim();
  const lines = input.split('\n');
  const totalNum = lines[0].split(' ')[0];
  const dislikeNum = lines[1].split(' ');
  const likeNum = [];
  for(var i = 0; i < 10; i++) {
    if(dislikeNum.indexOf(i + '') === -1) {
      likeNum.push(i + '');
    }
  }
  // var res = totalNum;
  // while(1) {
  //  var noMatch = false;
  //  for(var i = 0; i < res.length; i++) {
  //    if(dislikeNum.indexOf(res[i]) > -1) {
  //      res = parseInt(res) + 1;
  //      res = res + '';
  //      noMatch = true;
  //      break;
  //    }
  //  }
  //  if(!noMatch) {
  //    break;
  //  }
  // }
  // console.log(res);
  const res = getResult(totalNum, likeNum);
  if(res.flag) {
    console.log(likeNum[0] === '0' ? likeNum[1] + res.str : likeNum[0] + res.str);
  } else {
    console.log(res.str);
  }
}

function getResult(sourceNum, likeNum) {
  const item = sourceNum[0];
  const resObj = sourceNum.length - 1 ? getResult(sourceNum.slice(1), likeNum) : {};
  const resStr = resObj.str || '';
  const flag = resObj.flag;
  if(!flag) {
    if(likeNum.indexOf(item) > -1) {
      return {
        str: item + resStr,
        flag: false
      };
    } else {
      var bigger = getBigger(likeNum, item);
      if(bigger) {
        var str = '';
        for(var i = 0; i < resStr.length; i++) {
          str += likeNum[0];
        }
        return {
          str: bigger + str,
          flag: false
        };
      } else {
        var str = '';
        for(var i = 0; i < resStr.length; i++) {
          str += likeNum[0];
        }
        return {
          str: likeNum[0] + str,
          flag: true
        };
      }
    }
  } else {
    var bigger = getBigger(likeNum, item);
    if(bigger) {
      var str = '';
      for(var i = 0; i < resStr.length; i++) {
        str += likeNum[0];
      }
      return {
        str: bigger + str,
        flag: false
      };
    } else {
      var str = '';
      for(var i = 0; i < resStr.length; i++) {
        str += likeNum[0];
      }
      return {
        str: likeNum[0] + str,
        flag: true
      };
    }
  }
}

function getBigger(arr, num) {
  for(var i = 0; i < arr.length; i++) {
    if(arr[i] > num) {
      return arr[i] + ''
    }
  }
  return null;
}

main();


function Main(s) {
	s[0] = s[0].split(" ").map(a => parseInt(a));
	s[1] = s[1].split(" ").map(a => parseInt(a));
	var n = s[0][0];
	var k = s[0][1];
	var sl = s[1].length;
	while(f(n)) n++;

	console.log(n);

	function f(k){
		while(k){
			var m = k % 10;
			for(var i = 0; i < sl; i++){
				if(m === s[1][i]) return true;
			}
			k = Math.floor(k * 0.1);
		}
	}
}

Main(require("fs").readFileSync("/dev/stdin", "utf8").split("\n"));


function main(input) {
    let [totalPrice , length] = input.split("\n")[0].split(" ").map( v => Number(v));

    const list = JSON.parse(JSON.stringify(input.split("\n")[1].split(" ").map(v => Number(v))));
    const hateNumbers = { list, length };
    // const favoriteNumber = Array.from({ length: 10 }, (v, i) => i);
    // favoriteNumber.filter(v => hateNumbers.list.includes(v) ? false : true)

    const matches = new RegExp(`[${hateNumbers.list.join("")}]`);
    while (matches.test(totalPrice.toString())) {
        totalPrice++;
    }
    console.log('totalPrice', totalPrice);

}

// let input = "1000 8" + '\n' +
//     "1 3 4 5 6 7 8 9";
// main(input);
main(require("fs").readFileSync("/dev/stdin","utf8"));


function main() {
  process.stdin.resume();
  process.stdin.setEncoding("utf8");
  var chunks = "";

  process.stdin.on("data", function (chunk) {
    chunks += chunk;
  });

  process.stdin.on("end", function () {
    var inputs = chunks.trim().split("\n");
    var number = inputs[0].split(" ")[0].split("");
    var ks = inputs[1].split(" ").map((k) => parseInt(k, 10));
    var ans = [];

    var carry = false;
    for (i = number.length - 1; i >= 0; i--) {
      var n = parseInt(number[i], 10);
      if (carry) {
        n = n + 1;
        if (n >= 10) {
          n = 10 - n;
          carry = true;
        } else {
          carry = false;
        }
      }

      while (true) {
        if (ks.find((k) => k === n)) {
          n = n + 1;
          if (n >= 10) {
            n = 10 - n;
            carry = true;
          }
        } else {
          ans.unshift(n);
          break;
        }
      }
    }

    if (carry) {
      ans.unshift(1);
    }

    console.log(parseInt(ans.join(""), 10));
  });
}

main();


function main() {
  process.stdin.resume();
  process.stdin.setEncoding("utf8");
  var chunks = "";

  process.stdin.on("data", function (chunk) {
    chunks += chunk;
  });

  process.stdin.on("end", function () {
    var inputs = chunks.trim().split("\n");
    var number = inputs[0].split(" ")[0].split("");
    var ks = inputs[1].split(" ").map((k) => parseInt(k, 10));
    var ans = [];

    var carry = false;
    for (i = number.length - 1; i >= 0; i--) {
      var n = parseInt(number[i], 10);
      if (carry) {
        n = n + 1;
        if (n >= 10) {
          n = 10 - n;
          carry = true;
        } else {
          carry = false;
        }
      }

      while (true) {
        if (ks.find((k) => k === n)) {
          n = n + 1;
          if (n >= 10) {
            n = 10 - n;
            carry = true;
          }
        } else {
          ans.unshift(n);
          break;
        }
      }
    }

    if (carry) {
      ans.unshift(1);
    }

    console.log(ans);
  });
}

main();


package main

import "fmt"

func main() {
	var N, K int
	fmt.Scan(&N, &K)
	D := make([]bool, 10)
	for i := 0; i < K; i++ {
		var t int
		fmt.Scan(&t)
		D[t] = true
	}
	// fmt.Println("N", N, "K", K, "D", D)
	for v := N; v <= 1000000; v++ {
		ok := true
		t := v
		for t > 0 {
			if D[t%10] {
				ok = false
				break
			} else {
				t /= 10
			}
		}
		if ok {
			fmt.Println(v)
			return
		}
	}
}


package main

import (
	"fmt"
)

func main() {
	var n, k int
	fmt.Scan(&n, &k)
	d := make([]int, k)
	var e [10]bool
	var f []int
	for i := range d {
		fmt.Scan(&d[i])
		e[d[i]] = true
	}
	for i := 0; i < 10; i++ {
		if !e[i] {
			f = append(f, i)
		}
	}
	var x []int
	for n > 0 {
		x = append(x, n%10)
		n /= 10
	}
	p := len(x) - 1
	for p >= 0 {
		if e[x[p]] {
			break
		}
		p--
	}
	if p >= 0 {
		for {
			c := false
			j := x[p]
			for {
				j++
				if j == 10 {
					j = 0
					c = true
				}
				if !e[j] {
					break
				}
			}
			x[p] = j
			if !c {
				break
			}
			p++
			if p == len(x) {
				if f[0] == 0 {
					x = append(x, f[1])
				} else {
					x = append(x, f[0])
				}
				break
			}
		}
		for i := p - 1; i >= 0; i-- {
			x[i] = f[0]
		}
	}
	for i := len(x) - 1; i >= 0; i-- {
		fmt.Print(x[i])
	}
}


package main

import (
	"fmt"
	"strconv"
)

func main() {
	var n, k int
	fmt.Scan(&n, &k)
	dm := make(map[int]bool)
	var d int
	for i := 0; i < k; i++ {
		fmt.Scan(&d)
		dm[d] = true
	}
	gs := make([]int, 0)
	for i := 0; i <= 9; i++ {
		if !dm[i] {
			gs = append(gs, i)
		}
	}

	u := 0
	nums := make([]int, 0)
	s := strconv.Itoa(n)
	for i := len(s) - 1; i >= 0; i-- {
		ok := false
		c := int(s[i]-'0') + u
		uu := 0
		if c >= 10 {
			c = 0
			uu = 1
		}
		for _, d := range gs {
			if c <= d {
				nums = append(nums, d)
				ok = true
				u = 0 + uu
				if c < d {
					nums = update(nums, gs)
				}

				break
			}
		}
		if !ok {
			nums = append(nums, gs[0])
			u = 1
			nums = update(nums, gs)
		}
	}

	if u > 0 {
		for _, g := range gs {
			if g > 0 {
				nums = append(nums, g)
				break
			}
		}
		nums = update(nums, gs)
	}

	for i := len(nums) - 1; i >= 0; i-- {
		fmt.Print(nums[i])
	}
	fmt.Println()
}

func update(nums, gs []int) []int {
	for j := 0; j < len(nums)-1; j++ {
		nums[j] = gs[0]
	}
	return nums
}


package main

import (
	"fmt"
	"strconv"
	"strings"
)

//文字列に変換し、嫌いな数字を使っていないかを判断する関数
func convertNum(slice []int, hateNum []int) int {
	//入力された金額を文字列に変換する
	var priceStr string
	priceStr = strconv.Itoa(slice[0])
	//入力された'嫌いな数字'を文字列のスライスに変換し、文字列型に変換
	hateNumStr := make([]string, slice[1])
	for i := 0; i < slice[1]; i++ {
		hateNumStr[i] = strconv.Itoa(hateNum[i])
	}

	count := 0 //嫌いな数字の個数をカウントする変数
	//値段と嫌いな数字が被っているかを確認(被っている：true,被っていない:false)
	//全て被っていなかったら1を返し、１つでも被りがある場合は-1を返す
	for i := 0; i < slice[1]; i++ {
		//fmt.Print()
		//fmt.Println(strings.Contains(priceStr, hateNumStr[i]))

		if strings.Contains(priceStr, hateNumStr[i]) == false {
			count++
			if count == slice[1] {
				return 1
			}
		}
	}
	return -1
}

func main() {
	//値段と嫌いな数字の個数を入れるためのスライスを生成する
	slice := make([]int, 2)

	//標準入力
	//fmt.Println("値段と嫌いな数字の個数を入力してください。")
	fmt.Scanln(&slice[0], &slice[1])

	//代入できているか確認
	//fmt.Printf("値段は%d円で, 嫌いな数字の個数は%d個です。\n", slice[0], slice[1])

	//嫌いな数字を入力する
	hateNum := make([]int, slice[1])
	//fmt.Println("嫌いな数字を入力してください")
	for i := 0; i < slice[1]; i++ {
		fmt.Scan(&hateNum[i])
	}

	//嫌いな数字の確認用
	//fmt.Printf("嫌いな数字は%dです\n", hateNum)

	minPrice := slice //値段からインクリメントさせるための変数
	judge := -1       //convetNumから返ってくる値を代入する（-1はダメ、1はOK

	//条件が10000までの値なので、それに合わせる
	for i := 0; i < 10000-slice[0]; i++ {
		judge = convertNum(minPrice, hateNum)
		if judge == 1 {
			fmt.Printf("%d", minPrice[0])
			break
		}
		minPrice[0]++
	}
}


package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

func main() {
	var n, k int
	fmt.Scanf("%d %d", &n, &k)

	s := bufio.NewScanner(os.Stdin)
	s.Scan()
	split := strings.Split(s.Text(), " ")

	d := make([]int, k)
	for i, s := range split {
		d[i], _ = strconv.Atoi(s)
	}

	base := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
	fav := make([]int, 0, len(base)-k)
l1:
	for _, b := range base {
		for _, v := range d {
			if b == v {
				continue l1
			}
		}
		fav = append(fav, b)
	}

l2:
	for i := n; i < 10000; i++ {
		var ns []int
		ns = digit(i, ns)

		for j := 0; j < len(ns); j++ {
			var valid bool
			for _, v := range fav {
				if ns[j] == v {
					valid = true
				}
			}
			if !valid {
				continue l2
			}
		}

		fmt.Printf("%d", i)
		break
	}
}

func digit(i int, list []int) []int {
	if i > 0 {
		return digit(i/10, append(list, i%10))
	}
	return list
}


package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

func main() {
	var n, k int
	fmt.Scanf("%d %d", &n, &k)

	s := bufio.NewScanner(os.Stdin)
	s.Scan()
	split := strings.Split(s.Text(), " ")

	d := make([]int, k)
	for i, s := range split {
		d[i], _ = strconv.Atoi(s)
	}

	base := []int{0, 1, 2, 3, 4, 5, 6, 78, 8, 9}
	fav := make([]int, 0, len(base)-k)
l1:
	for _, b := range base {
		for _, v := range d {
			if b == v {
				continue l1
			}
		}
		fav = append(fav, b)
	}

l2:
	for i := n; i < 10000; i++ {
		var ns []int
		ns = digit(i, ns)

		for j := 0; j < len(ns); j++ {
			if ns[j] == 0 {
				continue
			}

			var valid bool
			for _, v := range fav {
				if ns[j] == v {
					valid = true
				}
			}
			if !valid {
				continue l2
			}
		}

		fmt.Printf("%d", i)
		break
	}
}

func digit(i int, list []int) []int {
	if i > 0 {
		return digit(i/10, append(list, i%10))
	}
	return list
}


N,K = gets.split.map(&:to_i)
D = gets.split.map(&:to_i)

ans = []
nums = 10.times.to_a - D
N.to_s.chars.reverse_each do |s|
  n = s.to_i
  m = nums.find {|m| n <= m }# || nums[0]
  ans.fill(nums[0]) if m && n < m
  ans.unshift(m)
end
ans.size.times.reverse_each do |i|
  next if ans[i]
  if i == 0
    ans.fill(nums[0]).unshift(nums.find {|m| 0 < m })
  else
    j = i - 1
    ans[i] = nums[0]
    ans[j] = nums.find {|m| ans[j] < m } if ans[j]
  end
end
puts ans.join


N, = gets.split
D = gets.split.map(&:to_i)

digits = ([*0..9]-D).sort
nz = digits[0]!=0 ? digits[0] : digits[1]

borrow = N.size-2-(N.each_char.reverse_each.with_index.inject(nil){|borrow, ci|
	n, i = ci[0].ord-'0'.ord, ci[1]
	m = digits.find{|d| borrow==i-1 ? n<d : n<=d }
	next m.nil? ? i : borrow
}||-2)
over = borrow==-1
p N.each_char.with_index.inject(borrow==-1?nz:0){|a,ci|
	n, i = ci[0].ord-'0'.ord, ci[1]
	m = over ? digits[0] : digits.find{|d| borrow == i ? n<d : n<=d }
	over ||= n<m
	next a*10 + m
}


N, K = gets.chomp.split
Ds = gets.chomp.split
Es = [*'0'..'9'] - Ds
tbl = {}
Es.each { |d| tbl[d] = true }

ms = ''
carry = false
N.reverse.chars do |c|
  c2 = c.dup
  c2.next! if carry
  c2.next! until tbl[c2] || c2.size > 1
  if c2.size == 1
    carry = false
  else
    c2 = Es[0]
    carry = true
  end
  ms = Es[0] * ms.size if c2 != c
  ms += c2
end
if carry
  ms += (Es[0] == '0' ? Es[1] : Es[0])
end

puts ms.reverse


n, k = gets.split.map &:to_i
d = gets.split.map &:to_i
digits = [*0..9] - d
l = digits.size
x = [0]
val = ->x{ x.inject(0) { |s, i| s * 10 + digits[i] } }
while val[x] < n
  if (x.size-1).downto(0).all? { |j|
    x[j] += 1
    if x[j] == l
      x[j] = 0
    else
      false
    end
    }
    x.unshift 1
  end
end

p val[x]


n, k = gets.split.map(&:to_i)
darr = gets.split.map(&:to_i)
uarr = (0..9).to_a - darr

num = -1
arr = Array.new(10, 0)
uarr.each do |n|
  (n - num).times do |j|
    arr[num + j + 1] = n
  end
  num = n
end

flag = false
snum_arr = n.to_s.chars
snum_arr.length.times do |i|
  num = snum_arr[i].to_i
  snum_arr[i] = flag ? arr[0].to_s : arr[num].to_s
  flag ||= arr[num] != num
end

snum_arr.unshift(arr[1].to_s) if snum_arr[0] == "0"
puts snum_arr.join


n, k = gets.split.map(&:to_i)
darr = gets.split.map(&:to_i)
uarr = (0..9).to_a - darr

arr = []
uarr.each do |n|
  l = arr.length
  (n - l + 1).times do |j|
    arr[l + j] = n
  end
end
l = arr.length
(10 - l).times do |i|
  arr[l + i] = 0
end

flag = false
snum_arr = n.to_s.chars
snum_arr.length.times do |i|
  num = snum_arr[i].to_i
  snum_arr[i] = flag ? arr[0].to_s : arr[num].to_s
  flag ||= arr[num] != num
end

snum_arr.unshift(arr[1].to_s) if snum_arr[0] == "0"
puts snum_arr.join


use std::str::FromStr;
use std::fmt::Debug;
use std::cmp;
#[allow(dead_code)]
fn read_as_vec<T>() -> Vec<T>
where T: FromStr, <T as FromStr>::Err : Debug{
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).unwrap();
    s.trim().split_whitespace().map(|c| T::from_str(c).unwrap()).collect()

}

#[allow(dead_code)]
fn read_as_string() -> String{
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).unwrap();
    s.trim().to_string()
}

fn main(){
    let line = read_as_vec::<u64>();
    let (n, _) = (line[0], line[1]);
    let d = read_as_vec::<u64>();

    'outer: for i in 1..n*10+1{
        if i < n{
            continue;
        }

        let mut x = i;
        while x > 0{
            if d.contains(&(x%10)){
                continue 'outer;
            }
            x /= 10;
        }
        println!("{}", i);
        return;
    }

    // let line = read_as_string();
    // let line: Vec<&str> = line.split_ascii_whitespace().collect::<Vec<&str>>();
    // let n: String = String::from(line[0]);
    // let k: u64 = u64::from_str(line[1]).unwrap();
    // let d = read_as_vec::<u64>();

    // let mut ans = 0;
    // let mut is_already_bigger = false;
    // for c in n.chars(){
    //     match d.iter().filter(|x| **x>= c.to_digit(10).unwrap() as u64).nth(0){
    //         Some(number) => {
    //             if is_already_bigger{
    //             }
    //             ans = ans*10+number;
    //             if *number > c.to_digit(10).unwrap() as u64{
    //                 is_already_bigger = true;
    //             }
    //         },
    //         None => {
    //             ans = ans*10
    //         }
    //     }
    // }

    // if ans >= n.parse().unwrap(){
    //     println!("{}", ans);
    //     return;
    // }
}


use std::io;

struct IrohaChan {
    digits: Vec<bool>,
}

impl IrohaChan {
    fn new(digits: Vec<usize>) -> Self {
        let mut available_digits = vec![true; 10];
        for i in digits {
            available_digits[i] = false;
        }
        IrohaChan{
            digits: available_digits,
        }
    }

    fn likes(&self, n: usize) -> bool {
        let mut k = n;
        while k > 0 {
            let d = k % 10;
            k /= 10;
            if !self.digits[d] {
                return false
            }
        }
        return true
    }

    fn purchase(&self, min_price: usize) -> usize {
        let mut i = min_price;
        loop {
            if self.likes(i) {
                return i
            }
            i += 1;
        }
    }
}

#[test]
fn test_iroha_likes_with_empty() {
    let iroha = IrohaChan::new(vec![]);
    assert!(iroha.likes(0));
    assert!(iroha.likes(1));
    assert!(iroha.likes(2));
    assert!(iroha.likes(3));
    assert!(iroha.likes(4));
    assert!(iroha.likes(5));
    assert!(iroha.likes(6));
    assert!(iroha.likes(7));
    assert!(iroha.likes(8));
    assert!(iroha.likes(9));

    assert!(iroha.likes(123));
    assert!(iroha.likes(456));
    assert!(iroha.likes(789));

    assert!(iroha.likes(12345));
    assert!(iroha.likes(67890));
}

#[test]
fn test_iroha_likes_with_singleton() {
    let iroha = IrohaChan::new(vec![3]);
    assert!(iroha.likes(0));
    assert!(iroha.likes(1));
    assert!(iroha.likes(2));
    assert!(!iroha.likes(3));
    assert!(iroha.likes(4));
    assert!(iroha.likes(5));
    assert!(iroha.likes(6));
    assert!(iroha.likes(7));
    assert!(iroha.likes(8));
    assert!(iroha.likes(9));

    assert!(!iroha.likes(123));
    assert!(iroha.likes(456));
    assert!(iroha.likes(789));

    assert!(!iroha.likes(12345));
    assert!(iroha.likes(67890));
}

#[test]
fn test_iroha_likes_with_multiple_digits() {
    let iroha = IrohaChan::new(vec![2, 8]);
    assert!(iroha.likes(0));
    assert!(iroha.likes(1));
    assert!(!iroha.likes(2));
    assert!(iroha.likes(3));
    assert!(iroha.likes(4));
    assert!(iroha.likes(5));
    assert!(iroha.likes(6));
    assert!(iroha.likes(7));
    assert!(!iroha.likes(8));
    assert!(iroha.likes(9));

    assert!(!iroha.likes(123));
    assert!(iroha.likes(456));
    assert!(!iroha.likes(789));

    assert!(!iroha.likes(12345));
    assert!(!iroha.likes(67890));

    assert!(!iroha.likes(28));
    assert!(iroha.likes(39));
}

#[test]
fn test_iroha_purchase_1() {
    let iroha = IrohaChan::new(vec![1, 3, 4, 5, 6, 7, 8, 9]);
    assert_eq!(iroha.purchase(1000), 2000)
}

#[test]
fn test_iroha_purchase_2() {
    let iroha = IrohaChan::new(vec![0]);
    assert_eq!(iroha.purchase(9999), 9999)
}

fn main() {
    let mut input = String::new();
    io::stdin().read_line(&mut input).unwrap();
    let mut iter = input.split_whitespace();

    let n: usize = iter.next().unwrap().parse().unwrap();
    let k: usize = iter.next().unwrap().parse().unwrap();

    let mut digits = Vec::with_capacity(k);
    let mut line = String::with_capacity(2 * k);
    io::stdin().read_line(&mut line).unwrap();
    for token in line.split_whitespace() {
        digits.push(token.parse().unwrap());
    }

    let iroha = IrohaChan::new(digits);

    println!("{}", iroha.purchase(n));
}


use std::io;

fn choose_digit(available_digits: &Vec<bool>, lower_digits: &mut Vec<usize>, d: usize) -> usize {
    if available_digits[d] {
        // println!("available: {}", d);
        lower_digits.push(d);
        return 0;
    }
    clear_lower_digits(&available_digits, lower_digits);
    // println!("cleared");
    for i in d+1..10 {
        if available_digits[i] {
            // println!("chosen: {}", i);
            lower_digits.push(i);
            return 0;
        }
    }
    lower_digits.push(0);
    return 1;
}

fn clear_lower_digits(available_digits: &Vec<bool>, ds: &mut Vec<usize>) {
    let mut d = 0;
    for i in 0..10 {
        // println!("i: {}", i);
        if available_digits[i] {
            d = i;
            break
        }
    }
    // println!("lowest digit: {}", d);
    let len = ds.len();
    for i in 0..len {
        ds[i] = d;
    }
}

fn main() {
    let mut input = String::new();
    io::stdin().read_line(&mut input).unwrap();
    let mut iter = input.split_whitespace();
    let mut n: usize = iter.next().unwrap().parse().unwrap();
    let k: usize = iter.next().unwrap().parse().unwrap();
    let mut available_digits = vec![true; 10];
    let mut line = String::with_capacity(2 * k);
    io::stdin().read_line(&mut line).unwrap();
    for token in line.split_whitespace() {
        let d: usize = token.parse().unwrap();
        available_digits[d] = false;
    }
    let mut digits = Vec::with_capacity(5);
    let mut carry = 0;
    while n > 0 {
        let d = n % 10 + carry;
        if d <= 9 {
            carry = choose_digit(&available_digits, &mut digits, d);
        } else {
            choose_digit(&available_digits, &mut digits, 0);
            carry = 1;
        }
        n = n / 10;
    }
    if carry > 0 {
        choose_digit(&available_digits, &mut digits, carry);
    }
    if digits.len() == 0 {
        println!("0");
        return
    }
    for d in digits.iter().rev() {
        print!("{}", d);
    }
    println!("");
}


use proconio::{input, fastout};
use proconio::marker::{Chars};
use proconio::marker::Usize1;
use std::cmp::*;

macro_rules! debug {
      ($($a:expr),*) => {
          eprintln!(concat!($(stringify!($a), " = {:?}, "),*), $($a),*);
    }
}

#[fastout]
fn main() {
    input!{
        n: usize,
        k: usize,
        d: [usize;k],
    }

    let mut ok: bool = true;
    let mut not_d: Vec<usize> = Vec::new();

    for i in 0..10 {
        for j in 0..k {
            if i!=d[j] {
                continue;
            } else {
                ok = false;
            }
        }
        if ok {
            not_d.push(i);
        } else {
            ok = true;
        }
    }
    ok = false;
    let nl = not_d.len();
    // debug!(not_d);
    for i in n..100000 {
        let mut x = i;
        while x!=0 {
            let r = x%10;
            if ok {
                ok = false;
            }
            for j in 0..nl {
                if r==not_d[j] {
                    ok = true;
                    break;
                }
                // debug!(not_d[j]);
            }
            x /= 10;
            // debug!(r);
            // debug!(ok);
        }
        if ok==true {
            println!("{}", i);
            return;
        }
    }

}


use proconio::{input, fastout};
use proconio::marker::{Chars};
use proconio::marker::Usize1;
use std::cmp::*;

macro_rules! debug {
      ($($a:expr),*) => {
          eprintln!(concat!($(stringify!($a), " = {:?}, "),*), $($a),*);
    }
}

#[fastout]
fn main() {
    input!{
        n: usize,
        k: usize,
        d: [usize;k],
    }

    let mut ok: bool = true;
    let mut not_d: Vec<usize> = Vec::new();

    for i in 0..10 {
        for j in 0..k {
            if i!=d[j] {
                continue;
            } else {
                ok = false;
            }
        }
        if ok {
            not_d.push(i);
        } else {
            ok = true;
        }
    }
    ok = false;
    let nl = not_d.len();
    // debug!(not_d);
    let mut i = n;
    loop {
        let mut x = i;
        while x!=0 {
            let r = x%10;
            if ok {
                ok = false;
            }
            for j in 0..nl {
                if r==not_d[j] {
                    ok = true;
                    break;
                }
                // debug!(not_d[j]);
            }
            x /= 10;
            // debug!(r);
            // debug!(ok);
        }
        if ok==true {
            println!("{}", i);
            return;
        } else {
            i += 1;
        }
    }

}


use proconio::{input, fastout};
use proconio::marker::{Chars};
use proconio::marker::Usize1;
use std::cmp::*;

macro_rules! debug {
      ($($a:expr),*) => {
          eprintln!(concat!($(stringify!($a), " = {:?}, "),*), $($a),*);
    }
}

#[fastout]
fn main() {
    input!{
        n: usize,
        k: usize,
        d: [usize;k],
    }

    let mut ok: bool = true;
    let mut not_d: Vec<usize> = Vec::new();

    for i in 0..10 {
        for j in 0..k {
            if i!=d[j] {
                continue;
            } else {
                ok = false;
            }
        }
        if ok {
            not_d.push(i);
        } else {
            ok = true;
        }
    }
    ok = false;
    let nl = not_d.len();
    // debug!(not_d);
    for i in n..10000 {
        let mut x = i;
        while x!=0 {
            let r = x%10;
            if ok {
                ok = false;
            }
            for j in 0..nl {
                if r==not_d[j] {
                    ok = true;
                    break;
                }
                // debug!(not_d[j]);
            }
            x /= 10;
            // debug!(r);
            // debug!(ok);
        }
        if ok==true {
            println!("{}", i);
            return;
        }
    }

}


//
//  main.swift
//  Atcoder
//
//  Created by Louis Joe Shen on 2020/7/17.
//  Copyright © 2020 Louise Joe Shen. All rights reserved.
//

import Foundation

var input = readLine()
var input2 = readLine()
var inputs = input!.components(separatedBy: " ")
var inputs2 = input2!.components(separatedBy: " ")

var N = Int(inputs[0])!
var K = Int(inputs[1])!

var D : [Int] = [Int]()

for i in 0 ..< K {
    D.append(Int(inputs2[i])!)
}

for i in N ... 666666 {
    if(isLike(number: i)){
        print(i)
        break;
    }
}
func isLike(number: Int) -> Bool {
    let delta = String(number)
    for c in delta {
        for dig in D {
            if(Int(String(c))! == dig){
                return false
            }
        }
    }
    return true;
}


let N = readLine()!.characters.split(" ").map{Int(String($0))!}[0]
let D = readLine()!.characters.split(" ").map{String($0)}
for i in N..<100000 {
    var flag = false
    for c in D {
        if String(i).characters.contains(Character(c)) {
            flag = false
            break
        } else {
            flag = true
        }
    }
    if flag {
        print(i)
        break
    }
}


import Foundation

            let values = readLine()!.characters.split{ x in x == " "}.map{Int(String($0))!}
            let N = values[0]
            let D = readLine()!.characters.split{ x in x == " "}.map{Int(String($0))!}

            for i in N ... 10000 {
                let str = String(i)
                for d in D {
                    if str.rangeOfString(String(d)) != nil {
                        continue
                    } else {
                        print(str)
                    }
                }
            }


            let values = readLine()!.characters.split{ x in x == " "}.map{Int(String($0))!}
            let N = values[0]
            let D = readLine()!.characters.split{ x in x == " "}.map{Int(String($0))!}

            for i in N ... 10000 {
                let str = String(i)
                for d in D {
                    if str.rangeOfString(String(d)) != nil {
                        continue
                    } else {
                        print(str)
                    }
                }
            }


            let values = readLine()!.characters.split{ x in x == " "}.map{Int(String($0))!}
            let N = values[0]
            let D = readLine()!.characters.split{ x in x == " "}.map{Int(String($0))!}

            for i in N ... 10000 {
                let str = String(i)
                for d in D {
                    if str.rangeOfString(String(d)) != nil {
                        continue
                    } else {
                        print(str)
                        return
                    }
                }
            }


import * as fs from 'fs'
const reader = (s: string) => s.split('\n')

function Main(input: string) {
  const [tmp, tmp2] = reader(input)
  const [N, K] = tmp.split(' ').map(x => parseInt(x, 10))
  const D = tmp2.split(' ')
  let ans = N

  while (1) {
    let count = 0
    for (const i of D) {
      if (ans.toString().indexOf(i) !== -1) {
        break
      }
      count++
    }
    if (count === K) {
      break
    }
    ans += 1
  }
  console.log(ans)
}

Main(fs.readFileSync('/dev/stdin', 'utf8'))


function main(input: string) {
  let num: number = Number(input.split(" ")[0]);
  const arrD: string[] = input
    .split("\n")
    .slice(1)
    .filter((val: string) => val !== "");
  const regD: RegExp = new RegExp(`[${arrD.join("")}]`, "g");
  while (num.toString().match(regD) != null) {
    num += 1;
  }
  console.log(num);
}

main(require("fs").readFileSync("/dev/stdin", "utf8"));


import * as fs from 'fs';
const input = fs.readFileSync("/dev/stdin", "utf8").split(/\n/);

// C-こだわり者いろはちゃん

let price = +input[0].split(' ')[0];
const dislikeNumbers = input[1].split(' ');
let flag: boolean = true;

while (flag === true) {
    flag = false;
    let target = String(price).split('');
    for (let i = 0; i < dislikeNumbers.length; i++) {
        if (target.indexOf(dislikeNumbers[i]) !== -1) {
            flag = true;
        }
    }

    if (flag === true) {
        price += 1;
    }
}

console.log(price);


const fs = require('fs')
const reader = (s: string) => (s.split("\n"))

function Main(input: string) {

  const [aaa,bbb] = reader(input);
  const D = bbb.split(' ');
  const [N,K] = aaa.split(' ').map(a => (parseInt(a)));

  if(K === 0)
  {
    console.log(N);
  }
  else
  {
    for(let i= N; i < 10000 ; i++)
    {
      if(D.every( d =>(!(i.toString().includes(d)))))
      {
        console.log(i);
        break;
      }
    }

  }

}

Main(fs.readFileSync('/dev/stdin', 'utf8'))


const fs = require('fs')
const reader = (s: string) => (s.split("\n"))

function Main(input: string) {

  const [aaa,bbb] = reader(input);
  const D = bbb.split(' ');
  const [N,K] = aaa.split(' ').map(a => (parseInt(a)));

  for(let i= N; i < 10000 ; i++)
  {
    if(D.every( d =>(!(i.toString().includes(d)))))
    {
      console.log(i);
      break;
    }
  }

}

Main(fs.readFileSync('/dev/stdin', 'utf8'))


const fs = require('fs')
const reader = (s: string) => (s.split("\n"))

function Main(input: string) {

  const [aaa,bbb] = reader(input);
  const D = bbb.split(' ');
  const [N,K] = aaa.split(' ').map(a => (parseInt(a)));

  for(let i= N; i < 10000 ; i++)
  {
    if(!D.some( d =>(i.toString().includes(d))))
    {
      console.log(i);
      break;
    }
  }

}

Main(fs.readFileSync('/dev/stdin', 'utf8'))


k = int(input())
cnt = [0] * (k + 1)

for i in range(k, 0, -1):
    cnt[i] = (k // i) ** 3
    for j in range(i * 2, k + 1, i):
        cnt[i] -= cnt[j]

print(sum((i* cnt[i] for i in range(1, k + 1))))


K =int(input())
l = [0, 1, 9, 30, 76, 141, 267, 400, 624, 885, 1249, 1590, 2208, 2689, 3411, 4248, 5248, 6081, 7485, 8530, 10248, 11889, 13687, 15228, 17988, 20053, 22569, 25242, 28588, 31053, 35463, 38284, 42540, 46581, 50893, 55362, 61824, 65857, 71247, 76884, 84388, 89349, 97881, 103342, 111528, 120141, 128047, 134580, 146316, 154177, 164817, 174438, 185836,194157,207927, 218812, 233268, 245277, 257857, 268182, 288216, 299257, 313635, 330204, 347836, 362973, 383709, 397042, 416448, 434025, 456967, 471948, 499740, 515581, 536073, 559758, 583960, 604833, 633651, 652216, 683712, 709065, 734233, 754734, 793188, 818917, 846603, 874512, 909496, 933081, 977145, 1006126, 1041504, 1073385, 1106467, 1138536, 1187112, 1215145, 1255101, 1295142, 1342852, 1373253, 1422195, 1453816, 1502376, 1553361, 1595437, 1629570, 1691292, 1726717, 1782111, 1827492, 1887772, 1925853, 1986837, 2033674, 2089776, 2145333, 2197483, 2246640, 2332104, 2379085, 2434833, 2490534, 2554600, 2609625, 2693919, 2742052, 2813988, 2875245, 2952085, 3003306, 3096024, 3157249, 3224511, 3306240, 3388576, 3444609, 3533637, 3591322, 3693924, 3767085, 3842623, 3912324, 4027884, 4102093, 4181949, 4270422, 4361548, 4427853, 4548003, 4616104, 4718640, 4812789, 4918561, 5003286, 5131848, 5205481, 5299011, 5392008, 5521384, 5610705, 5739009, 5818390, 5930196, 6052893, 6156139, 6239472, 6402720, 6493681, 6623853, 6741078, 6864016, 6953457, 7094451, 7215016, 7359936, 7475145, 7593865, 7689630, 7886244, 7984165, 8130747, 8253888, 8403448, 8523897, 8684853, 8802826, 8949612, 9105537, 9267595, 9376656, 9574704, 9686065, 9827097, 9997134, 10174780, 10290813,10493367, 10611772,10813692]
print(l[K])


ans = [1, 9, 30, 76, 141, 267, 400, 624, 885, 1249, 1590, 2208, 2689, 3411, 4248, 5248, 6081, 7485, 8530, 10248, 11889, 13687, 15228, 17988, 20053, 22569, 25242, 28588, 31053, 35463, 38284, 42540, 46581, 50893, 55362, 61824, 65857, 71247, 76884, 84388, 89349, 97881, 103342, 111528, 120141, 128047, 134580, 146316, 154177, 164817, 174438, 185836, 194157, 207927, 218812, 233268, 245277, 257857, 268182, 288216, 299257, 313635, 330204, 347836, 362973, 383709, 397042, 416448, 434025, 456967, 471948, 499740, 515581, 536073, 559758, 583960, 604833, 633651, 652216, 683712, 709065, 734233, 754734, 793188, 818917, 846603, 874512, 909496, 933081, 977145, 1006126, 1041504, 1073385, 1106467, 1138536,
1187112, 1215145, 1255101, 1295142, 1342852, 1373253, 1422195, 1453816, 1502376, 1553361, 1595437, 1629570, 1691292, 1726717, 1782111, 1827492, 1887772, 1925853, 1986837, 2033674, 2089776, 2145333, 2197483, 2246640, 2332104, 2379085, 2434833, 2490534, 2554600, 2609625, 2693919, 2742052, 2813988, 2875245, 2952085, 3003306, 3096024, 3157249, 3224511, 3306240, 3388576, 3444609, 3533637, 3591322, 3693924, 3767085, 3842623, 3912324, 4027884, 4102093, 4181949, 4270422, 4361548, 4427853, 4548003, 4616104, 4718640, 4812789, 4918561, 5003286, 5131848, 5205481, 5299011, 5392008, 5521384, 5610705, 5739009, 5818390, 5930196, 6052893, 6156139, 6239472, 6402720, 6493681, 6623853, 6741078, 6864016, 6953457, 7094451, 7215016, 7359936, 7475145, 7593865, 7689630, 7886244, 7984165, 8130747, 8253888, 8403448, 8523897, 8684853, 8802826, 8949612, 9105537, 9267595, 9376656, 9574704, 9686065, 9827097, 9997134, 10174780, 10290813,
10493367, 10611772, 10813692]
k = int(input())
print(ans[k-1])


import math
from functools import reduce

def gcd(*numbers):
    return reduce(math.gcd,numbers)

n =int(input())
c=0
for i in range(1,n+1):
    for j in range(1,n+1):
        for k in range(1,n+1):
            c+=gcd(i,j,k)
print(c)


K = int(input())
total = 0

def gcd2(a,b): #互除法
  while True:
    mod = a % b
    if mod == 0:
      return b
    a = b
    b = mod

memo = {}
def gcd(a,b,c):
  a,b,c = sorted([a,b,c])
  if (a,b,c) not in memo:
    val = gcd2(gcd2(a,b), c)
    memo[(a,b,c)] = val
    return val
  return memo[(a,b,c)]

for a in range(1, K+1):
  for b in range(1, K+1):
    for c in range(1, K+1):
      g = gcd(a, b, c)
#      print(a,b,c, g)
      total += g

print(total)


import math
k=int(input())

ans=0
for i in range(k):
  for j in range(k):
    q=math.gcd(i,j)
    for l in range(k):
      ans+=math.gcd(q,l+1)
print(ans)


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

class Main {
	public static void main(String[] args) throws IOException {
		Scan sc = new Scan();
		int K = sc.scanInt();
		SolABC162_c sol = new SolABC162_c(K);
		sol.calcMu();
		sol.calcGCDTuple(3);
	}
}

class SolABC162_c {
	int K;
	int[] mu, prime;

	public SolABC162_c(int K) {
		this.K = K;
		mu = new int[K + 1];
		prime = new int[K + 1];
		for (int i = 1; i <= K; ++i) {
			mu[i] = 1;
			prime[i] = 1;
		}
	}

	void calcMu() {
		for (int i = 2; i <= K; ++i) {
			if (prime[i] == 1) {
				for (int j = i; j <= K; j += i) {
					if (j > i)
						prime[j] = 0;
					if (j % (i * i) == 0)
						mu[j] = 0;
					mu[j] = -mu[j];
				}
			}
		}
	}

	void calcGCDTuple(int cnt) {
		long res = 0;
		for (int d = 1; d <= K; ++d) {
			long tmp = 0;
			for (int s = 1; s <= K / d; ++s) {
				tmp += (mu[s] * Math.pow(K / (d * s), cnt));
			}
			res += tmp * d;
		}
		System.out.println(res);
	}
}

class Scan {
    private byte[] buf=new byte[1024];
    private int index;
    private InputStream in;
    private int total;

    public Scan()
    {
        in=System.in;
    }
    public int scan()throws IOException
    {
        if(total<0)
        throw new InputMismatchException();
        if(index>=total)
        {
            index=0;
            total=in.read(buf);
            if(total<=0)
            return -1;
        }
        return buf[index++];
    }
    public int scanInt()throws IOException
    {
        int integer=0;
        int n=scan();
        while(isWhiteSpace(n))
        n=scan();
        int neg=1;
        if(n=='-')
        {
            neg=-1;
            n=scan();
        }
        while(!isWhiteSpace(n))
        {
            if(n>='0'&&n<='9')
            {
                integer*=10;
                integer+=n-'0';
                n=scan();

            }
            else throw new InputMismatchException();
        }
        return neg*integer;
    }
	public long scanLong()throws IOException
    {
        long integer=0;
        int n=scan();
        while(isWhiteSpace(n))
        n=scan();
        int neg=1;
        if(n=='-')
        {
            neg=-1;
            n=scan();
        }
        while(!isWhiteSpace(n))
        {
            if(n>='0'&&n<='9')
            {
                integer*=10;
                integer+=n-'0';
                n=scan();
            }
            else throw new InputMismatchException();
        }
        return neg*integer;
    }
    public double scanDouble()throws IOException
    {
        double doub=0;
        int n=scan();
        while(isWhiteSpace(n))
        n=scan();
        int neg=1;
        if(n=='-')
        {
            neg=-1;
            n=scan();
        }
        while(!isWhiteSpace(n)&&n!='.')
        {
            if(n>='0'&&n<='9')
            {
                doub*=10;
                doub+=n-'0';
                n=scan();
            }
            else throw new InputMismatchException();
        }
        if(n=='.')
        {
            n=scan();
            double temp=1;
            while(!isWhiteSpace(n))
            {
                if(n>='0'&&n<='9')
                {
                    temp/=10;
                    doub+=(n-'0')*temp;
                    n=scan();
                }
                else throw new InputMismatchException();
            }
        }
        return doub*neg;
    }
    public String scanString()throws IOException
    {
        StringBuilder sb=new StringBuilder();
        int n=scan();
        while(isWhiteSpace(n))
        n=scan();
        while(!isWhiteSpace(n))
        {
            sb.append((char)n);
            n=scan();
        }
        return sb.toString();
    }
    private boolean isWhiteSpace(int n)
    {
        if(n==' '||n=='\n'||n=='\r'||n=='\t'||n==-1)
        return true;
        return false;
    }
}