PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#SP0000173. Nguyên tố hoán vị chữ số (Anagrammatic Primes)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Nguyên tố hoán vị chữ số (Anagrammatic Primes)

Anagrammatic Primes

Phuoc Hung OJ ID: PRIME000178
Original source: UVa 897

Problem statement

An anagrammatic prime remains prime under every permutation of its digits. Given nn, find the next such prime without crossing the next power-of-ten boundary.

Input

One positive integer nn.

Output

Print the smallest anagrammatic prime xx with n<x<10kn<x<10^k, where 10k10^k is the smallest power of ten greater than nn; print 0 if none exists.

Subtasks

  • Subtask 1 (20 points): 1≤n≤91\le n\le 9.
  • Subtask 2 (30 points): 10≤n≤99910\le n\le 999.
  • Subtask 3 (50 points): 1 000≤n≤9 999 9991\,000\le n\le 9\,999\,999.

Example

Input

900

Output

919

Explanation: The distinct permutations of 919919 are 919,991,199919,991,199, all prime, and it is the first qualifying number greater than 900900.