VOOZH about

URL: https://www.geeksforgeeks.org/dsa/calculate-the-sum-of-gcd-over-all-subarrays/

⇱ Calculate the Sum of GCD over all subarrays - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Calculate the Sum of GCD over all subarrays

Last Updated : 12 Jul, 2025

Given an array of integers, the task is to calculate the sum of GCD of all the subarrays of an array. GCD of an array is defined as the GCD of all the elements present in it. More formally, . Summation of all the GCDs can be defined as where denotes the subarray starting from ith index and ending at jth index.
Examples: 
 

Input 1: N = 5, A = {1,2,3,4,5} 
Output 1: 25
Explanation: 
The subarrays of length one are [1], [2], [3], [4], [5] and the sum of their GCDs is 15, similarly subarrays of length 2, are [1, 2], [2, 3], [3, 4], [4, 5], and the sum of their GCDs is 4, similarly for length 3, the sum is 3, similarly for length 4, the sum is 2, similarly for length 5, the sum is 1. 
The total sum becomes 25.
Input 2: N = 6, A = {2,2,2,3,5,5} 
Output 2: 41 
 


Pre-Requisites 
Binary Search 
Segment Tree approach for calculating GCD in an index range 
Sparse Table for calculating GCD in an index range
 


Naive Approach (O(n^3) complexity)
We can find out every subarray in O(n^2) complexity and can traverse it for finding the GCD of that subarray and add it to the total answer.
Below is the implementation of the above approach: 
 


Output: 
25

 

Time Complexity: O(N^3)

Space Complexity: O(1)

We can optimize the part where you calculate GCD of a subarray, We can use a segment tree or a sparse table to optimize the complexity to O(n^2 * logn) (for segment trees) or to O(n^2) (for sparse table)
Efficient Approach (O(n*(logn)^2) complexity):
This approach takes advantage of the observation that upon adding a new element to an array, the new GCD of the array will always be either less or equal to the previous GCD of the array before the addition of the element.
We create three pointers, lets call them startPointer, endPointer and prevEndPointer. Initially all three of them point to the first element of our array. We initialize a variable tempGCD with the value of the first element. We will now find the sum of GCDs of all the subarrays starting with first element. 
Now according to our previous observation, if we move the endPointer to the right by one position, and calculate the GCD of these two elements which are pointed by startPointer and endPointer, it will always be less than or equal to tempGCD. So if we want to find out how many subarrays have the GCD as tempGCD, we need to find a suitable position of endPointer, where the subarray starting at startPointer and ending at endPointer will have the value of it's GCD less than tempGCD, and the value of endPointer should be as minimal as possible, then the difference of prevEndPointer and endPointer will give us the number of subarrays which have their GCD as tempGCD. Now, we can add this value (tempGCD*(endPointer-prevEndPointer)), which denotes the sum of the GCD for these particular group of subarrays, into our variable finalAns which stores the sum of the GCD of all subarrays. 
Now the question remains, how will we find the suitable position of endPointer where the GCD decreases? That's where Binary Search comes into use, we have the starting point of our array fixed, and we need to vary the ending point, let's call them L and R, so for any R. We initialize high as N and low as prevEndPointer, and mid as (high+low)/2, now if we check the value of GCD[L, mid], we compare it to the value of tempGCD, and if it is less than it, then R might be a suitable position for endPointer, but it might be the case that some smaller value may become our answer, so we change high to be mid-1, and if GCD[L, mid] is found to be equal to tempGCD, then we should change low to be mid+1, and the value of mid+1 might be the answer, so we store the value of mid in a variable nextPos. At last we return the value of nextPos+1
Value of GCD[L, mid] can be efficiently calculated using a Segment Tree in O(logN) complexity or using a Sparse Table in O(1) complexity. 
This type of binary search finds us the suitable position of endPointer. After finding out this position, and adding to finalAns, we change prevEndPointer to endPointer, and tempGCD to GCD[startPointer, endPointer], and again start the process of finding next endPointer. This will stop once the value of endPointer becomes N, and then we need to move startPointer to the right, which will count the sum of GCD of all subarrays starting with second element. This will continue till the value of startPointer becomes N.
Below is the implementation of the above approach: 
 


Output: 
41

 

Time Complexity: O(N * log(max(A[i]) * log(N)) 
The time complexity of the above solution includes the knowledge of knowing how many times the binary search will be called, and hence we need to know how many times value of endPointer may change. This value comes out to be approximately log(A[i]), because, for any number X, the number of times it's GCD can decrease upon being clubbed with other number is the value of highest power of any of it's prime divisors. So the total time complexity becomes approximately O(N * log(max(A[i]) * log(N)) where another logN factor comes due to Binary search. This is the case when we use Sparse Table, if we use Segment Tree for GCD queries, another term of log(N) will appear.
 

Related Topic: Segment Tree

Comment