Tower Breakers, Revisited!


Problem Statement :


cTwo players (numbered  and ) are playing a game of Tower Breakers! The rules of the game are as follows:

Player  always moves first, and both players always move optimally.
Initially there are  towers of various heights.
The players move in alternating turns. In each turn, a player can choose a tower of height  and reduce its height to , where  and  evenly divides .
If the current player is unable to make any move, they lose the game.
Given the value of  and the respective height values for all towers, can you determine who will win? If the first player wins, print ; otherwise, print .

Input Format

The first line contains an integer, , denoting the number of test cases.
Each of the  subsequent lines defines a test case. Each test case is described over the following two lines:

An integer, , denoting the number of towers.
 space-separated integers, , where each  describes the height of tower .

Output Format

For each test case, print a single integer denoting the winner (i.e., either  1  or  2 ) on a new line.



Solution :



title-img


                            Solution in C :

In  C  :






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

int main() {
    long long int q,t,s,i,j,n,k=0,p,temp;
     scanf("%lld",&t);
    for(q=0;q<t;q++){
        scanf("%lld",&n);
        s=0;
        for(i=0;i<n;i++)
        {scanf("%lld",&j);
         k=0;
         //if(j>1){k=1;}
         temp=j;
         for(p=2;p<=sqrt(temp);p++){
             if(j%p==0){
                 while(j%p==0){
                     if(j<=1){break;}
                     j=j/p;
                     k++;
                 }
             }
         }
         if(j>1){k++;}
        s=s^k;               
        }
        if(s==0){printf("2\n");}
        else printf("1\n");
    }
   
    return 0;
}
                        


                        Solution in C++ :

in  C++  :





#include<stdio.h>
#include<algorithm>

using namespace std;

const int maxi=1e6+5;

int cnt[maxi],b[maxi];
int p,q,ans,n,t,tmp,xs,m;

void solve()
{
  scanf("%d",&n);

   xs=0;
  for (int i=0;i<n;i++)
   {
       scanf("%d",&p);
       xs=xs^cnt[p];
    }

    if (xs==0) printf("2\n"); else printf("1\n");
}

void sito()
{
    cnt[1]=0;

    for (int i=2;i<maxi;i++)
    {
        if (b[i]==0)
        {
          for (int j=i;j<maxi;j+=i)
          {
              m=j;
              b[j]=1;
              while (m%i==0)
              {
                cnt[j]++;
                m=m/i;
              }

          }
        }
    }
}

int main()
{
    scanf("%d",&t);

    sito();

    while (t--)
       solve();

  return 0;
}
                    


                        Solution in Java :

In  Java  :







import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {
//Day 2: Tower Breakers revisited
	static ArrayList<Integer> p;

    public static boolean isPrime(int i){//odd primes only
        for(int j=0;j<p.size() && p.get(j)<=Math.sqrt(i);j++){
            if(i%p.get(j)==0) return false;
        }
        return true;    
    }
    
    public static int divNo(int n){
        if(n==1) return 0;
        
        int count = 0;
        boolean prime = true;
        //add primes if necessary
        if(p.get(p.size()-1) < n){ 
            for(int i=p.get(p.size()-1)+2; i<=n;i+=2){
                if(isPrime(i)) p.add(i);
            }
        }
        
        for(int i=0,j=n; j>1 && p.size()>i && p.get(i)<=j;i++){
            while(j%p.get(i)==0) {//p[i] divides j
                j/=p.get(i); count++; prime=false;
            }
        }
        if(!prime) return count;
        else return 1;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int t = in.nextInt();
        int [] s = new int[100];
        int [] q = new int[100];
        p =  new ArrayList<Integer>(Arrays.asList(2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97));
        int i,j,n,m;
        for(int tt =0;tt<t;tt++){
            n = in.nextInt();
            
            for(i=0;i<n;i++){
                s[i] = in.nextInt();
                q[i] = divNo(s[i]);
            }
            int nimsum = q[0];
            for(i = 1;i<n;i++){
                nimsum^=q[i];
            }
            
            if(nimsum>0) System.out.println("1");
            else System.out.println("2");   
        }
    }
}
                    


                        Solution in Python : 
                            
In  Python3 :






import random

from fractions import gcd
from itertools import product

def composite(a, d, n, s):
    if pow(a, d, n) == 1:
        return False
    for i in range(s):
        if pow(a, 2**i * d, n) == n-1:
            return False
    return True

def millerrabin(n):
    if n == 1:
        return False
    if n in [2, 31, 73]:
        return True
    if n % 2 == 0:
        return False
    d = n - 1
    s = 0
    while d % 2 == 0:
        d >>= 1
        s += 1
    for a in [31, 73]:
        if composite(a, d, n, s):
            return False
    return True

def pollard(n):
    if n % 2 == 0:
        return 2
    a = random.randint(-100, 100)
    while a == -2:
        a = random.randint(-100, 100)
    x = random.randint(1, 1000)
    y = x
    d = 1
    while d == 1:
        x = (pow(x, 2, n) + a) % n
        y = (pow(y, 2, n) + a) % n
        y = (pow(y, 2, n) + a) % n
        d = gcd(abs(x - y), n)
        if d == n:
            break
    return d

def rho_factor(n):
    if n == 1:
        return {1: 0}
    divisors = [n]
    factors = []
    while divisors:
        d = divisors.pop()
        if millerrabin(d):
            factors.append(d)
            continue
        new_d = pollard(d)
        if d == new_d:
            divisors.append(d)
            continue
        divisors.extend([new_d, d // new_d])
    factor_n = {}
    for x in set(factors):
        factor_n[x] = factors.count(x)
    return factor_n

def grundy(n):
    return sum(v for _, v in rho_factor(n).items())

def towers(array):
    ans = 0
    while array:
        ans ^= grundy(array.pop())
    return [1, 2][ans == 0]

def main():
    for _ in range(int(input())):
        n, array = input(), [int(x) for x in input().split()]
        print(towers(array))

if __name__ == '__main__':
    main()
                    


View More Similar Problems

Binary Search Tree : Lowest Common Ancestor

You are given pointer to the root of the binary search tree and two values v1 and v2. You need to return the lowest common ancestor (LCA) of v1 and v2 in the binary search tree. In the diagram above, the lowest common ancestor of the nodes 4 and 6 is the node 3. Node 3 is the lowest node which has nodes and as descendants. Function Description Complete the function lca in the editor b

View Solution →

Swap Nodes [Algo]

A binary tree is a tree which is characterized by one of the following properties: It can be empty (null). It contains a root node only. It contains a root node with a left subtree, a right subtree, or both. These subtrees are also binary trees. In-order traversal is performed as Traverse the left subtree. Visit root. Traverse the right subtree. For this in-order traversal, start from

View Solution →

Kitty's Calculations on a Tree

Kitty has a tree, T , consisting of n nodes where each node is uniquely labeled from 1 to n . Her friend Alex gave her q sets, where each set contains k distinct nodes. Kitty needs to calculate the following expression on each set: where: { u ,v } denotes an unordered pair of nodes belonging to the set. dist(u , v) denotes the number of edges on the unique (shortest) path between nodes a

View Solution →

Is This a Binary Search Tree?

For the purposes of this challenge, we define a binary tree to be a binary search tree with the following ordering requirements: The data value of every node in a node's left subtree is less than the data value of that node. The data value of every node in a node's right subtree is greater than the data value of that node. Given the root node of a binary tree, can you determine if it's also a

View Solution →

Square-Ten Tree

The square-ten tree decomposition of an array is defined as follows: The lowest () level of the square-ten tree consists of single array elements in their natural order. The level (starting from ) of the square-ten tree consists of subsequent array subsegments of length in their natural order. Thus, the level contains subsegments of length , the level contains subsegments of length , the

View Solution →

Balanced Forest

Greg has a tree of nodes containing integer data. He wants to insert a node with some non-zero integer value somewhere into the tree. His goal is to be able to cut two edges and have the values of each of the three new trees sum to the same amount. This is called a balanced forest. Being frugal, the data value he inserts should be minimal. Determine the minimal amount that a new node can have to a

View Solution →