![]() |
VOOZH | about |
Given an integer N denoting the number of boxes in a pen, and two players P1 and P2 playing a game of distributing N pens among themselves as per the following rules:
The task to print the following details once the game is over:
Examples:
Input: N = 22
Output:
Number of pens remaining in the box: 14
Number of pens collected by P1 : 5
Number of pens collected by P2 : 3
Explanation:
- Move 1: X = 0, P1 takes 1 pen from the box. Therefore, N = 22 - 1 = 21.
- Move 2: X = 1, P2 takes 3 pens from the box. Therefore, N = 21 - 3 = 18.
- Move 3: X = 2, P1 takes 4 pens from the box. Therefore, N = 18 - 4 = 14.
- Move 4: X = 3, P2 quits as 27 > 14.
- Move 5: X = 4, P1 quits as 16 > 14.
- Game Over! Both players have quit.
Input: N = 1
Output:
Number of pens remaining in the box : 0
Number of pens collected by P1 : 1
Number of pens collected by P2 : 0
Approach: The idea is to use Recursion. Follow the steps to solve the problem:
1. Define a recursive function:
Game_Move(N, P1, P2, X, Move, QuitP1, QuitP2)
where,
N : Total number of Pens
P1 : Score of P1
P2 : Score of P2
X : Initialized to zero
Move = 0 : P1's turn
Move = 1 : P2's turn
QuitP1 : Has P1 quit
QuitP2 : Has P2 quit
2. Finally, print the final values after the game has ended
Below is the implementation of the above-mentioned approach:
Number of pens remaining in the box: 14 Number of pens collected by P1: 5 Number of pens collected by P2: 3
Time Complexity: O(Log(N))
Auxiliary Space: O(1)