Tower
Time limit1sMemory limit512 MB
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 . Alan stacks the cuboids one on top of another.

Figure 1: A tower of three bricks when Alan fixes .
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.
- The side length of the first square is .
- Alan fixes the side length of the second square himself.
- For , the side length is computed as . Do not ask why he chose this formula; let us just say he is a truly peculiar young fellow.
For example, if Alan fixes , then (see Figure 1). If Alan fixes , then holds for every (see Figure 2).

Figure 2: A tower of four bricks when Alan fixes .
Now Alan wonders whether he can compute the volume of a tower made of consecutive bricks. Since each cuboid's volume is (base area) (height) , the volume of the whole tower is . Because this value can be quite large, it is enough to output the answer modulo a given natural number .
Input
The input contains several test cases. The first line contains the number () of test cases. Then test cases follow. Each test case is given on a single line containing three integers , , (, ) separated by a single space, where is the fixed side length of the second square from step 2 and is the number of bricks Alan builds.
Output
For each test case , output on its own line the volume of the tower of consecutive bricks built according to rules (1)–(3), taken modulo .