forked from adityabisoi/ds-algo-solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
solution.cpp
64 lines (60 loc) · 1.87 KB
/
solution.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/*
Imagine each tower as a Nim pile which has a Nimvalue equal to the number of prime factors of hi.
Reducing a tower to its divisor is the same as taking away a non-zero prime factor from it.
Thus, this game is the same as a Nim game and our answer is the XOR of all Nim piles.
If the Nim sum is 0, then player 2wins;
otherwise, player 1 wins.
*/
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
// Cool problem! Trick is to realize that each tower is really a nim heap of size # of prime factors
int main() {
int T;
cin>>T;
while(T > 0) {
int N;
cin>>N;
long tmp, nimSum = 0;
for(int i = 0; i < N; i++) {
cin>>tmp;
// Determine number of prime factors
int numPrimeFactors = 0;
if(tmp == 1) {
numPrimeFactors = 0;
} else if(((tmp != 0) && !(tmp & (tmp - 1)))) {
// If tmp is a power of 2
numPrimeFactors = tmp/2;
} else {
// Calculate # of prime factors
while(tmp > 1) {
bool foundFactor = false;
for(long j = 2; j*j <= tmp; j++) {
if(tmp%j == 0) {
numPrimeFactors++;
tmp /= j;
foundFactor = true;
break;
}
}
if(!foundFactor) {
// tmp is prime
numPrimeFactors++;
break;
}
}
}
nimSum ^= numPrimeFactors;
}
if(nimSum != 0) {
cout<<"1\n";
} else {
cout<<"2\n";
}
T--;
}
return 0;
}