After looking at other approaches for this problem, I realized that it was a simple problem and I was just making it complex. But still, I am unable to find a mistake in my approach.
What I tried to do is, I made a segment tree using the code :
void segtree(int node, int b, int e) {
if (b == e){
st[node] = in[b];
}else{
segtree(2 * node + 1, b, (b + e) / 2);
segtree(2 * node + 2, (b + e) / 2 +1, e);
st[node] = (st[2*node+ 1]*st[2*node + 2])/gcd(st[2*node+ 1],st[2*node + 2]);
}
}
Now, in this segment tree, each node contains the factors, contained by both of its child-nodes.
Further then, I started with one of the leaves, and moved through the tree, using recursion, checking if node has gcd(curent_node, the_value_of_the_leaf) > 1. If the condition is true, I enter into the childs of that node.
In this way, I was saving the maximum depth that we can reach from all the leaves, and was saving that into a dp[] array.
For answer I was just taking the max value in the dp[].
The actual code is kind of clumsy but - CodeChef: Practical coding for everyone
or the code in plain-text form - https://www.codechef.com/viewplaintext/12252520