You just bought a game of monsters which consists of various levels consisting of monsters. Each monster has power βPβ associated with it. Each monster follows (βPβ * βPβ + 1) % βMβ distinct monsters in the next level having values from 0 to [(βPβ * βPβ + 1) % βMβ] - 1 where βMβ is a modulo integer given to you. Find the total number of monsters in all levels you need to finish to clear the game.
Note :
In the first level, there is only one monster with power, βPβ = 2.
The first line of input contains an integer βTβ, the number of test cases.
The first line of each test case contains two single space-separated integers βLβ and βMβ representing the number of levels and the modulo integer respectively.
Output Format :
For each test case, print a single integer modulo βMβ representing the number of monsters.
Print the output of each test case in a separate line.
Note :
You do not need to print anything, it has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= L <= 10
3 <= M <= 50
Time Limit : 1 sec
2
2 4
1 5
2
1
For first test case :
Level 1: The number of monsters is 1 with power 2. So the number of monster in next level will be ((2 * 2) + 1) % 4 i.e. 5 % 4 = 1. And the power of next level monster will be from 0 to [((2 * 2) + 1) % 4] - 1 i.e. 0 to 0.
Level 2: The number of monsters is 1 with power 0.
We reached the last level, so the total number of monsters will be 2.
For second test case :
As there is only 1 level present, so the number of monsters will be 1.
Think of finding monsters at each level.
The basic idea is to pre-compute monsters from 0 to βMβ levels. Monster at any level cannot be more than βMβ since we are using βMβ as modulo at each level for the number of monsters. We use a queue to traverse the monsters at each level and push the monsters of a new level into the queue.
Here is the algorithm :
O(L * M), where βLβ is the number of levels and βMβ is the given modulo integer.
We traverse at each level to count the number of monsters, and at each level, we can have the maximum βMβ number of monsters that we traverse using the queue. Therefore, the overall time complexity will be O(L * M).
O(M), where βMβ is the given modulo integer.
We use an array of size of βMβ to store the number of monsters by doing pre-computation. We also use a queue to store the monsters at each level which can have a maximum βMβ size. Therefore, the overall space complexity will be O(M).