This page is still under construction.

Parts of this page are still being built. What you see may change.

Digit Sum Depth

Time limit2sMemory limit512 MB

Summary
Given N, m, and base l, find the smallest positive integer whose iterated base-l digit sum takes exactly N steps to fall below l, and output it modulo m.
Level

Hard8 of 10

Topics
Number theory, Math
Solved
No attempts yet

Problem

For a positive integer aa, let S(a)S(a) be the sum of the digits of aa written in base ll. Let L(a)L(a) be the smallest kk with Sk(a)≤l−1S^k(a) \leq l-1, where S0(a)=aS^0(a) = a and Sk(a)=S(Sk−1(a))S^k(a) = S(S^{k-1}(a)) for k≥1k \geq 1.

Given NN, find the smallest positive integer aa with L(a)=NL(a) = N and print that value modulo mm.

Input

The input has several test cases. Each test case is one line with three integers NN, mm, ll (0≤N≤1050 \leq N \leq 10^5, 1≤m≤1091 \leq m \leq 10^9, 2≤l≤1092 \leq l \leq 10^9).

The last line contains 0 0 0. That line is not a test case.

Output

For each test case, print one line of the form Case x: y. Here xx is the test case number starting at 1, and yy is the smallest such aa modulo mm.

Examples3

  1. Example 1

    Input
    0 1000 10
    1 1000 10
    0 0 0
    
    Expected output
    Case 1: 1
    Case 2: 10
    
  2. Example 2

    Input
    2 100 3
    3 100 3
    4 100 3
    0 0 0
    
    Expected output
    Case 1: 5
    Case 2: 17
    Case 3: 21
    
  3. Example 3

    Input
    0 1000 2
    1 1000 2
    2 1000 2
    3 1000 2
    4 1000 2
    5 1000 2
    6 1000 2
    0 0 0
    
    Expected output
    Case 1: 1
    Case 2: 2
    Case 3: 3
    Case 4: 7
    Case 5: 127
    Case 6: 727
    Case 7: 727