Skip to content
Related Articles

Related Articles

Maximum GCD of all subarrays of length at least 2
  • Difficulty Level : Medium
  • Last Updated : 04 Mar, 2021

Given an array arr[] of N numbers. The task is to find the maximum GCD of all subarrays of size greater than 1. 
Examples: 
 

Input: arr[] = { 3, 18, 9, 9, 5, 15, 8, 7, 6, 9 } 
Output:
Explanation: 
GCD of the subarray {18, 9, 9} is maximum which is 9.
Input: arr[] = { 4, 8, 12, 16, 20, 24 } 
Output:
Explanation: 
GCD of the subarray {4, 18, 12, 16, 20, 24} is maximum which is 4. 
 

 

Naive Approach: The idea is to generate all the subarray of size greater than 1 and then find the maximum of gcd of all subarray formed. 
Time complexity: O(N2) 
Efficient Approach: Let GCD of two numbers be g. Now if we take gcd of g with any third number say c then, gcd will decrease or remain same, but it will never increase. 
The idea is to find gcd of every consecutive pair in the arr[] and the maximum of gcd of all the pairs formed is the desired result.
Below is the implementation of the above approach: 
 

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find GCD
int gcd(int a, int b)
{
    if (b == 0) {
        return a;
    }
    return gcd(b, a % b);
}
 
void findMaxGCD(int arr[], int n)
{
 
    // To store the maximum GCD
    int maxGCD = 0;
 
    // Traverse the array
    for (int i = 0; i < n - 1; i++) {
 
        // Find GCD of the consecutive
        // element
        int val = gcd(arr[i], arr[i + 1]);
 
        // If calculated GCD > maxGCD
        // then update it
        if (val > maxGCD) {
            maxGCD = val;
        }
    }
 
    // Print the maximum GCD
    cout << maxGCD << endl;
}
 
// Driver Code
int main()
{
    int arr[] = { 3, 18, 9, 9, 5,
                  15, 8, 7, 6, 9 };
 
    int n = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    findMaxGCD(arr, n);
    return 0;
}

Java




// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function to find GCD
static int gcd(int a, int b)
{
    if (b == 0)
    {
        return a;
    }
    return gcd(b, a % b);
}
 
static void findMaxGCD(int arr[], int n)
{
 
    // To store the maximum GCD
    int maxGCD = 0;
 
    // Traverse the array
    for(int i = 0; i < n - 1; i++)
    {
         
       // Find GCD of the consecutive
       // element
       int val = gcd(arr[i], arr[i + 1]);
        
       // If calculated GCD > maxGCD
       // then update it
       if (val > maxGCD)
       {
           maxGCD = val;
       }
    }
 
    // Print the maximum GCD
    System.out.print(maxGCD + "\n");
}
 
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 3, 18, 9, 9, 5,
                  15, 8, 7, 6, 9 };
    int n = arr.length;
 
    // Function call
    findMaxGCD(arr, n);
}
}
 
// This code is contributed by amal kumar choubey

Python3




# Python3 program for the above approach
 
# Function to find GCD
def gcd(a, b):
     
    if (b == 0):
        return a;
    return gcd(b, a % b);
 
def findMaxGCD(arr, n):
     
    # To store the maximum GCD
    maxGCD = 0;
 
    # Traverse the array
    for i in range(0, n - 1):
 
        # Find GCD of the consecutive
        # element
        val = gcd(arr[i], arr[i + 1]);
 
        # If calculated GCD > maxGCD
        # then update it
        if (val > maxGCD):
            maxGCD = val;
 
    # Print the maximum GCD
    print(maxGCD);
 
# Driver Code
if __name__ == '__main__':
     
    arr = [ 3, 18, 9, 9, 5,
            15, 8, 7, 6, 9 ];
    n = len(arr);
 
    # Function call
    findMaxGCD(arr, n);
 
# This code is contributed by 29AjayKumar

C#




// C# program for the above approach
using System;
 
class GFG{
 
// Function to find GCD
static int gcd(int a, int b)
{
    if (b == 0)
    {
        return a;
    }
    return gcd(b, a % b);
}
 
static void findMaxGCD(int []arr, int n)
{
 
    // To store the maximum GCD
    int maxGCD = 0;
 
    // Traverse the array
    for(int i = 0; i < n - 1; i++)
    {
         
        // Find GCD of the consecutive
        // element
        int val = gcd(arr[i], arr[i + 1]);
             
        // If calculated GCD > maxGCD
        // then update it
        if (val > maxGCD)
        {
            maxGCD = val;
        }
    }
 
    // Print the maximum GCD
    Console.Write(maxGCD + "\n");
}
 
// Driver Code
public static void Main()
{
    int []arr = { 3, 18, 9, 9, 5,
                 15, 8, 7, 6, 9 };
    int n = arr.Length;
 
    // Function call
    findMaxGCD(arr, n);
}
}
 
// This code is contributed by Code_Mech

Javascript




<script>
 
// Javascript program for the above approach
 
// Function to find GCD
function gcd(a, b)
{
    if (b == 0) {
        return a;
    }
    return gcd(b, a % b);
}
 
function findMaxGCD(arr, n)
{
 
    // To store the maximum GCD
    let maxGCD = 0;
 
    // Traverse the array
    for (let i = 0; i < n - 1; i++) {
 
        // Find GCD of the consecutive
        // element
        let val = gcd(arr[i], arr[i + 1]);
 
        // If calculated GCD > maxGCD
        // then update it
        if (val > maxGCD) {
            maxGCD = val;
        }
    }
 
    // Print the maximum GCD
    document.write(maxGCD + "<br>");
}
 
// Driver Code
  
    let arr = [ 3, 18, 9, 9, 5,
                15, 8, 7, 6, 9 ];
 
    let n = arr.length;
 
    // Function Call
    findMaxGCD(arr, n);
 
// This code is contributed by Mayank Tyagi
 
</script>
Output: 
9

 

Time Complexity: O(N), where N is the length of the array.
 

Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :