#P3896. Lucky Numbers Square Sum

    ID: 17144 Type: Default 1000ms 256MiB

Lucky Numbers Square Sum

Lucky Numbers Square Sum

A clever rabbit defined three functions on non‐negative integers based on their decimal representations (possibly with leading zeros):

  • \(g(x)\) is the number formed by arranging the digits of \(x\) in non‐increasing order (from high to low order).
  • \(l(x)\) is the number formed by arranging the digits of \(x\) in non‐decreasing order (from high to low order).
  • \(f(x)=g(x)-l(x)\).

A number \(x\) is called a lucky number if \(x = f(x)\). For example, when \(n=3\) (i.e. considering all three-digit numbers including those with leading zeros) one can verify that besides the trivial case \(000\), \(495\) is lucky since \[ 495=954-459\] Similarly, for \(n=4\) the number \(6174\) satisfies \[ 6174=7641-1467\] Note that any number with all digits equal gives \(f(x)=0\) and thus only \(000\) (or \(0000\)) is lucky in that case.

Given two integers \(n\) and \(p\), where \(n\) is the number of digits (the numbers are considered with possible leading zeros) and \(p\) is a modulus, compute the sum of squares of all lucky numbers among the \(n\)-digit numbers, and output the answer modulo \(p\). Based on known properties of the Kaprekar routine:

  • For \(n=3\), the lucky numbers are \(000\) and \(495\), so the answer is \(0^2+495^2\) modulo \(p\).
  • For \(n=4\), the lucky numbers are \(0000\) and \(6174\), so the answer is \(0^2+6174^2\) modulo \(p\).
  • For any other \(n\) (including \(n=1,2\) or \(n\ge5\)), the only lucky number is the trivial \(0\); hence the answer is \(0\).

inputFormat

The input consists of two space‐separated integers:

  • n — the number of digits (numbers are considered with possible leading zeros).
  • p — the modulus.

outputFormat

Output a single integer, the sum of the squares of all the lucky numbers among all \(n\)-digit numbers, taken modulo \(p\).

sample

3 1000
25