@ssrivastava990 Bro i think your GCD calculation time complexity is O(n^2) , that’s what giving you TLE
I’ll tell you my method, you basically need to reduce that O(n^2)
The question can be divided into two parts
Task 1. For all possible subarrays, find their GCD and no of times the occur i.e frequency
Task 2. like @l_returns said, use sieve method for queries. I’ll explain my answer in detail.
My Solution which i’m refering
Line No 162 to 165 => Variable Declaration
Line No 166 to 169 => I build my sparse table, that can give me GCD of any range in log(n) time
Line No 170=> I create a map which would map a GCD with its frequency
Line No 171 to 182 => THIS IS WHERE I CALCULATE GCD WITH THEIR FREQUENCY
Basically GCD if calculated from a index, will either decrease or stay constant. Hence it’s monotonic in nature, so i can use binary search.
Line No 142 to 154 => MY Binary Search function that returns the index of the position where GCD decreases
I start with any index and call it my original GCD. Now I binary search the index where it decreases. Now i use my original index and that index to calculate the increase in the frequency of that GCD, by using the difference in index.
So in nlog(n) time i calculated all possible GCD with their frequency.
So Task 1 Complete Yay!
Now coming to task #2, it’s easy
Line No 186=> I call a function, fillDp();
Line No 197 to 202 => I’m using the sieve method here, i take any GCD (say X) and i add its frequency to all multiples of that GCD, simple! You can learn more about Sieve method from internet
So for all query ‘q’ , we simply outout the dp[q].
Task 2 accomplished ! and time for AC ![]()
Let me know if any part of solution is unclear?

…but i knew that the changed GCD can only be equal to
zada samajh me aaega.what i did was for every subarray i used to find the gcd and then mark it in the seive so finding gcd for each subarray took o(n^2logn) time how did you reduced it using sparse table and binary search that i want to know…