I am solving the following problem:

Given an array of N (N<=5*10^5) numbers. Consider the GCD of all the subarrays and print the no. of distinct GCD's found over all subarrays. A[i]<=10^18.

I am using the fact that for a fixed element A[i], GCD decreases as we increase the subarray length starting from element A[i]. So I considered all subarrays starting from index i and using binary search + sparse matrix(for range gcd) computed the indices where GCD changes and inserted the GCDs in a set and did the same for all other indices. But getting TLE. Please suggest some optimization or some other approach for this problem.

My code: https://ideone.com/zeDVkD

The number of different gcd values of consecutive subsequences headed by A[i] is at most log(n)，so we can save these gcd values for every A[i], the different gcd values generated by A[i+1] are used to update the different gcd values generated by A[i]. so it cost O(nlogn) time complexity and space complexity。

This is an extension of the original problem: You are asked to answer q queries. Each query asks how many different gcd values are in the interval [l,r]。

freeloop2 Thanks for the reply . Can you explain this line " the different gcd values generated by A[i+1] are used to update the different gcd values generated by A[i]. so it cost O(nlogn) time complexity and space complexity" a bit more ??

Different gcd values of consecutive subsequences headed by A[i] equals gcd(A[i], Different gcd values of consecutive subsequences headed by A[i+1] ).

freeloop2 Thanks got accepted , didn't know about log(n) factor before this problem. Can you provide the link to the query version of this problem??

OK，here is the link: Different GCD Subarry Query have fun!

Thanks a lot.

Can you post a link to the question?