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

Merging Communities

People connect with each other in a social network. A connection between Person I and Person J is represented as . When two persons belonging to different communities connect, the net effect is the merger of both communities which I and J belongs to. At the beginning, there are N people representing N communities. Suppose person 1 and 2 connected and later 2 and 3 connected, then ,1 , 2 and 3 w

View Solution →

Components in a graph

There are 2 * N nodes in an undirected graph, and a number of edges connecting some nodes. In each edge, the first value will be between 1 and N, inclusive. The second node will be between N + 1 and , 2 * N inclusive. Given a list of edges, determine the size of the smallest and largest connected components that have or more nodes. A node can have any number of connections. The highest node valu

View Solution →

Kundu and Tree

Kundu is true tree lover. Tree is a connected graph having N vertices and N-1 edges. Today when he got a tree, he colored each edge with one of either red(r) or black(b) color. He is interested in knowing how many triplets(a,b,c) of vertices are there , such that, there is atleast one edge having red color on all the three paths i.e. from vertex a to b, vertex b to c and vertex c to a . Note that

View Solution →

Super Maximum Cost Queries

Victoria has a tree, T , consisting of N nodes numbered from 1 to N. Each edge from node Ui to Vi in tree T has an integer weight, Wi. Let's define the cost, C, of a path from some node X to some other node Y as the maximum weight ( W ) for any edge in the unique path from node X to Y node . Victoria wants your help processing Q queries on tree T, where each query contains 2 integers, L and

View Solution →

Contacts

We're going to make our own Contacts application! The application must perform two types of operations: 1 . add name, where name is a string denoting a contact name. This must store name as a new contact in the application. find partial, where partial is a string denoting a partial name to search the application for. It must count the number of contacts starting partial with and print the co

View Solution →

No Prefix Set

There is a given list of strings where each string contains only lowercase letters from a - j, inclusive. The set of strings is said to be a GOOD SET if no string is a prefix of another string. In this case, print GOOD SET. Otherwise, print BAD SET on the first line followed by the string being checked. Note If two strings are identical, they are prefixes of each other. Function Descriptio

View Solution →