Do the Untwist
Time limit1sMemory limit128 MB
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 , a positive integer.
Twisting uses four arrays of length , where 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 to . Every message consists only of lowercase letters, the period, and the underscore (which stands for a space).
Given a key , 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 from to ,
Here is the non-negative remainder of divided by (for example, , , and ). 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 gives:
Your task is to untwist messages: given the key , recover the original plaintext from the ciphertext. For instance, with key 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 , which marks the end of the input. Each test case is on a line by itself and consists of the key , a single space, and then a twisted message of at least and at most characters. The key is a positive integer no greater than .
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 and the length equals , which is guaranteed for every test case.)
Output
For each test case, print the untwisted message on a line by itself.