Because we are using gcd to transfer numbers, so the number which shares the same factor should in the same set. So we could use Union-Find to mark numbers.
There is also a tricky point that how to get the prime factor of one number.
constint N = 1E5+1; classSolution { int p[N]; staticboolcmp(int& a, int &b){return a < b;} public: voidmerge(int a, int b){ int x = find(a), y = find(b); if(x != y){ p[x] = y; } }