Do the Untwist

Time limit1sMemory limit128 MB

Summary
Given a key and a twisted ciphertext, invert the twisting formula to recover the original plaintext message.
Level

Easy3 of 10

Topics
Math, Implementation
Solved
No attempts yet

Problem

Cryptography studies methods of secret communication that transform a message (the plaintext) into a disguised form (the ciphertext) so that no one who sees the ciphertext can recover the plaintext except the intended recipient. Turning the plaintext into the ciphertext is encryption; turning the ciphertext back into the plaintext is decryption. Twisting is a simple encryption method in which the sender and recipient agree in advance on a secret key kk, a positive integer.

Twisting uses four arrays of length nn, where nn is the length of the message: plaintext and ciphertext hold characters, while plaincode and ciphercode hold integers. All arrays are zero-indexed, so their elements are numbered from 00 to n−1n-1. Every message consists only of lowercase letters, the period, and the underscore (which stands for a space).

Given a key kk, encryption proceeds as follows. First map each character of plaintext to an integer in plaincode using the rule

_ = 0, a = 1, b = 2, …, z = 26, . = 27.

Then compute each entry of ciphercode from plaincode: for every ii from 00 to n−1n-1,

ciphercode[i]=(plaincode[ki mod n]−i) mod 28.\text{ciphercode}[i] = (\text{plaincode}[k i \bmod n] - i) \bmod 28.

Here x mod yx \bmod y is the non-negative remainder of xx divided by yy (for example, 3 mod 7=33 \bmod 7 = 3, 22 mod 8=622 \bmod 8 = 6, and −1 mod 28=27-1 \bmod 28 = 27). Finally, map the integers in ciphercode back to characters in ciphertext using the same rule as above; the result is the twisted message.

For example, twisting cat with key 55 gives:

Array012
plaintextcat
plaincode3120
ciphercode31927
ciphertextcs.

Your task is to untwist messages: given the key kk, recover the original plaintext from the ciphertext. For instance, with key 55 and ciphertext cs., your program must output the plaintext cat.

Input

The input contains one or more test cases, followed by a line containing only the number 00, which marks the end of the input. Each test case is on a line by itself and consists of the key kk, a single space, and then a twisted message of at least 11 and at most 7070 characters. The key kk is a positive integer no greater than 300300.

You may assume that untwisting a message always yields a unique result. (For readers familiar with number theory: this holds whenever the greatest common divisor of the key kk and the length nn equals 11, which is guaranteed for every test case.)

Output

For each test case, print the untwisted message on a line by itself.

Examples1

  1. Example 1

    Input
    5 cs.
    101 thqqxw.lui.qswer
    3 b_ylxmhzjsys.virpbkr
    0
    
    Expected output
    cat
    this_is_a_secret
    beware._dogs_barking