Under construction

Still being built. Things may change

Composite Prime

Time limit1sMemory limit1024 MB

Summary
Given up to 1e5 queries with N as large as 10^7, find the largest composite number at most N whose every proper contiguous digit substring of length 2 or more is prime.
Level

Medium6 of 10

Topics
Backtracking, Math, Binary search, String
Solved
No attempts yet

Problem

13131313 factors as 13×10113 \times 101, so it is composite. However, every proper contiguous subnumber of 13131313 made from at least two consecutive digits, namely 1313, 3131, 1313, 131131, and 313313, is prime.

For a positive integer NN with at least three digits, define a proper contiguous subnumber as follows. Take two or more consecutive digits from the decimal representation of NN, keep their order, and interpret the result as a nonnegative integer. The number NN itself is excluded.

A positive integer NN is called a composite prime if all three conditions below hold.

  • NN has at least three digits.
  • NN is composite.
  • Every proper contiguous subnumber of NN is prime.

A proper contiguous subnumber may start with 00, and the value 00 itself is possible. For example, the proper contiguous subnumbers of 2002320023 include 2020, 00(=0)00(=0), 02(=2)02(=2), 2323, 200200, 002(=2)002(=2), 023(=23)023(=23), 20022002, and 0023(=23)0023(=23). Since 2020 is not prime, 2002320023 is not a composite prime.

Given a positive integer NN, find the largest composite prime not greater than NN.

Input

The first line contains the number of test cases TT. (1≤T≤105)(1 \le T \le 10^5)

Each of the next TT lines contains one integer NN. (1≤N≤107)(1 \le N \le 10^7)

Output

For each test case, print the largest composite prime not greater than NN on its own line. If no such number exists, print −1-1 instead.

Print the answers in the same order as the input test cases.

Examples1

  1. Example 1

    Input
    8
    100
    200
    300
    400
    600
    800
    1000
    1200
    
    Expected output
    -1
    171
    297
    371
    597
    737
    979
    1137