This page is still under construction.

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

Tower

Time limit1sMemory limit512 MB

Summary
For t up to 1e5 cases, given a2, N, and m, compute the sum of squares of the first N terms of the recurrence a1=1, an=2*a2*a(n-1)-a(n-2), modulo m.
Level

Medium7 of 10

Topics
Math, Number theory, Matrix, Divide and conquer
Solved
No attempts yet

Problem

Alan loves to build towers out of building bricks. His towers consist of many cuboids with a square base. All cuboids have the same height h=1h = 1. Alan stacks the cuboids one on top of another.

Figure 1: A tower of three bricks when Alan fixes a2=2a_2 = 2.

Recently, in math class, Alan learned about the concept of volume, so now he wants to compute the volume of his tower. Going from top to bottom, the side length of each cuboid's square base is defined as follows.

  1. The side length a1a_1 of the first square is 11.
  2. Alan fixes the side length a2a_2 of the second square himself.
  3. For n>2n > 2, the side length ana_n is computed as an=2a2an−1−an−2a_n = 2 a_2 a_{n-1} - a_{n-2}. Do not ask why he chose this formula; let us just say he is a truly peculiar young fellow.

For example, if Alan fixes a2=2a_2 = 2, then a3=8−a1=7a_3 = 8 - a_1 = 7 (see Figure 1). If Alan fixes a2=1a_2 = 1, then an=1a_n = 1 holds for every n∈Nn \in \mathbb{N} (see Figure 2).

Figure 2: A tower of four bricks when Alan fixes a2=1a_2 = 1.

Now Alan wonders whether he can compute the volume of a tower made of NN consecutive bricks. Since each cuboid's volume is (base area) ×\times (height) =an2= a_n^2, the volume of the whole tower is ∑n=1Nan2\sum_{n=1}^{N} a_n^2. Because this value can be quite large, it is enough to output the answer modulo a given natural number mm.

Input

The input contains several test cases. The first line contains the number tt (t≤105t \le 10^5) of test cases. Then tt test cases follow. Each test case is given on a single line containing three integers a2a_2, NN, mm (1≤a2,m≤1091 \le a_2, m \le 10^9, 2≤N≤1092 \le N \le 10^9) separated by a single space, where a2a_2 is the fixed side length of the second square from step 2 and NN is the number of bricks Alan builds.

Output

For each test case (a2,N,m)(a_2, N, m), output on its own line the volume ∑n=1Nan2\sum_{n=1}^{N} a_n^2 of the tower of NN consecutive bricks built according to rules (1)–(3), taken modulo mm.

Examples3

  1. Example 1

    Input
    3
    2 3 100
    1 4 1000
    3 3 1000000000
    
    Expected output
    54
    4
    299
    
  2. Example 2

    Input
    1
    5 2 1000
    
    Expected output
    26
    
  3. Example 3

    Input
    1
    1 1000000000 7
    
    Expected output
    6