Vampire Numbers

Time limit10sMemory limit128 MB

Summary
Given X, find the smallest vampire number at or above X, where a vampire number splits into two factors whose combined digits match its own digits.
Level

Medium4 of 10

Topics
Brute force, Implementation, Math
Solved
No attempts yet

Problem

18271827 is an interesting number because 1827=21×871827 = 21 \times 87, and the digits used on the left-hand side and the right-hand side are exactly the same. 136948136948 has a similar property: 136948=146×938136948 = 146 \times 938.

Numbers like these are called vampire numbers. That is, for vv to be a vampire number it must be possible to write it as a product of two numbers aa and bb (v=a×bv = a \times b) such that the digits appearing in aa and bb together are exactly the digits of vv, counting repetitions. None of vv, aa, bb may have a leading zero.

Because aa and bb would normally have to be the same length, vv would have to have an even number of digits; but in this problem, aa and bb having different lengths is also allowed for a vampire number.

Here are some examples of vampire numbers.

126=6×21126 = 6 \times 21

10251=51×20110251 = 51 \times 201

702189=9×78021702189 = 9 \times 78021

29632=32×92629632 = 32 \times 926

Given a number XX, write a program that finds the smallest vampire number greater than or equal to XX.

Input

The input consists of several test cases. Each test case is a single line containing an integer XX (10≤X≤1,000,00010 \le X \le 1{,}000{,}000). The input ends with a line containing 00.

Output

For each test case, output the smallest vampire number greater than or equal to XX, one per line.

Hint

Vampire numbers are a genuine mathematical concept (see Wikipedia: Vampire number).

Examples1

  1. Example 1

    Input
    10
    126
    127
    5000
    0
    
    Expected output
    126
    126
    153
    6880