Solving problems at CodeForces is a kind of hobby. Lately, in round 449, division 2, there was a problem which has met my interest.
It has to do with palindromes and really big numbers. The problem is easy to calculate, but once the numbers become quite big, it is not easy to get inside the two seconds time per test. This is how the problem looks like:
If a number is palindrome and length of its decimal representation without leading zeros is even, we call it a zcy number. A number is palindrome means when written in decimal representation, it contains no leading zeros and reads the same forwards and backwards. For example 12321 and 1221 are palindromes and 123 and 12451 are not. Moreover, 1221 is zcy number and 12321 is not.
Given integers k and p, calculate the sum of the k smallest zcy numbers and output this sum modulo p.
Unfortunately, Willem isn’t good at solving this kind of problems, so he asks you for help!
The first line contains two integers k and p (1 ≤ k ≤ 105, 1 ≤ p ≤ 109).
Output single integer — answer to the problem.
What is the idea behind this problem? Of course, not to loop through every number and to check whether it is a zcy palindrome, but to generate these zcy palindromes by yourself and to see the sum of the first k. Then find Sum[k] % p. The generation of the palindromes is not difficult, as far as we use a function, named ReverseAndMake(). It uses the fact, that we need only the zcy palindromes which can be generated as a simple mirroring of a sequence. E.g., 11, 22, 33, 44, 55, 66, 77, 88, 99, 1001, 1111 are the first 11. The other tricky part is to use “BigInteger”, as far as the sum of the first 10^5 zcy numbers sounds like huge.
Here comes the code:
static void Main()
List<BigInteger> inputList = ReadLineAndParseToList();
BigInteger k = inputList;
BigInteger p = inputList;
BigInteger sumOfK = 0;
for (BigInteger i = 1; i <= k; i++)
sumOfK += ReverseAndMake(i);
public static BigInteger ReverseAndMake(BigInteger intS)
string s = intS.ToString();
char charArray = s.ToCharArray();
return BigInteger.Parse(s + new string(charArray));
public static List<BigInteger> ReadLineAndParseToList()