Palindromes
Time limit1sMemory limit128 MB
For each number in a small interval written in base b, apply reverse-and-add up to l times and count how many do not reach a palindrome.
- Level
Medium7 of 10
- Topics
- Simulation, Math, String, Implementation
- Solved
- No attempts yet
Problem
Willi took part in a programming contest. One of the tasks was to check whether given strings were palindromes — strings that read the same forwards and backwards. Solving it earned him the point he needed for victory, so he decided to spend some of his free time exploring palindromes further. He realized that numbers can be palindromes too: for example, is a palindrome.
After a while, Willi noticed the following: "If a number is not a palindrome, I can turn it into one by adding the number with its digits reversed." For instance, is not a palindrome, but adding its reverse gives , which is a palindrome.
Playing with this on paper, he found numbers for which one step is not enough, such as . Adding its reverse yields , which is not a palindrome. His fix: if the result is not a palindrome, simply repeat the reverse-and-add step until a palindrome appears. In this example, , a palindrome.
But does this always work?
Because Willi got bored with the problem, he asks for your help. Write a program that, for every number in an interval , checks whether repeatedly reversing the number and adding it to itself produces a palindrome. To make sure your program terminates, he also gives you the maximum number of iterations to apply.
Since Willi is curious — and does not have to do the work himself — he wants you to check this for numbers written in an arbitrary base, not just decimal.
Input
The first line of input contains the number of test cases . Each test case starts with a line containing the base and the maximum number of iterations , separated by a space. The next line contains two strings and , separated by a space, written in base ; they denote the start and end of the interval to test.
The values satisfy the following limits:
- The base of the numbers: .
- The number of iterations : .
- and each have fewer than digits, and the interval contains only a small number of values (at most a few hundred).
Digit values greater than are written with lowercase letters ().
Output
The output for each test case begins with a line Scenario i:, where is the number of the scenario, starting at .
For each scenario, every number in the interval is tested to see whether repeatedly adding its digit-reversal produces a palindrome within iterations. (A number that is already a palindrome is considered to terminate in iterations.)
The next line contains the count of numbers for which no termination of the algorithm within iterations could be shown.