STACK - Stack
Alan loves to construct a stack of building bricks. His stack consists of many cuboids with square base. All cuboids have the same height 1. Alan puts the consecutive cuboids one over another.
Recently in math class, the concept of volume was introduced to Alan. Consequently, he wants to compute the volume of his stack now. The lengths of cuboids bases (from top to bottom) are constructed by Alan in the following way:
- Length of edge of the first square is one. i.e. a1 = 1.
- Next, Alan fixes the length of the edge of the second square a2.
- Next, Alan calculates the length an (n > 2) by 2*a2*an-1 - an-2. Do not ask why he chose such a formula; let us just say that he is a really peculiar young fellow.
For example, if Alan fixes a2 = 2, then a3 = 7. If Alan fixes a2 = 1, then an = 1 holds for all n.
Now Alan wonders if he can calculate the volume of stack of N consecutive building bricks. Help Alan and write the program that computes this volume. Since it can be quite large, it is enough to compute the answer modulo given natural number m.
The input contains several test cases. The first line contains the number t (t <= 100000) denoting the number of test cases. Then t test cases follow. Each of them is given in a separate line containing three integers a2, N, m (1 <= a2, m <= 109, 2 <= N <= 109) separated by a single space.
For each test case compute the volume of stack of N consecutive bricks constructed by Alan according to steps 1 to 3 and output its remainder modulo m.
Input: 3 2 3 100 1 4 1000 3 3 1000000000 Output: 54 4 299
Warning: large input/output data, be careful with certain languages
Warning: A naive algorithm won't terminate in even 2 minutes.