In this HackerRank Tower Breakers problem solution, Two players are playing a game of Tower Breakers! Player 1 always moves first, and both players always play optimally. The rules of the game are as follows:

  1. Initially, there are N towers.
  2. Each tower is of height M.
  3. The players move in alternating turns.
  4. In each turn, a player can choose a tower of height X and reduce its height to Y, where 1 <= Y < X and Y evenly divide X.

If the current player is unable to make a move, they lose the game.

Given the values of N and M, determine which player will win. If the first player wins, return 1. Otherwise, return 2.

HackerRank Tower Breakers problem solution


Problem solution in Python.

T = int(input())
for t in range(T):
    n, m = [int(x) for x in input().strip().split()]
    if m == 1: 
        print(2)
    else:
        if n % 2 == 1:
            print(1)
        else:
            print(2)


Problem solution in Java.

import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
        Scanner in = new Scanner(System.in);
        int T = in.nextInt();
        int N, M;
        while (T-- > 0) {
            N = in.nextInt();
            M = in.nextInt();
            System.out.println((M != 1 && N%2 == 1)? 1 : 2 );

        }
    }
}


Problem solution in C++.

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;


int main() {
        int n,x,y;
    cin>>n;
    do{
        cin>>x>>y;
       (y==1||x%2==0)?cout<<"2"<<endl:cout<<"1"<<endl;
         n--;
    }while(n>0);
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */  
    return 0;
}


Problem solution in C.

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main() {
    int n;
    scanf("%d", &n);
    for(int testcase = 0; testcase < n; testcase++) {
        int num_towers;
        int height;
        scanf("%d %d", &num_towers, &height);
        
        if(height == 1 || num_towers % 2 == 0)
            printf("2\n");
        else
            printf("1\n");
    }
    return 0;
}