Open In App

Python program to Find the Jumbo GCD subarray

Given an array, write a program to find the maximum GCD among all the subarray of the size >= 2 of the given array.

Examples:



Input list: [2, 3, 4, 4, 4]
Output: 4

Input list: [3, 7, 2, 9, 18, 5, 1, 13 ]
Output: 9

Approach:

Below you can find the implementation of the above-mentioned approach:
Examples 1: 




import math
 
# input list
List = [2, 3, 4, 4, 4 ]
 
max1 = 0
for i in range(len(List)-1):
   
  # use math.gcd() function
  gcd1 = math.gcd(List[i], List[i + 1])
  if(gcd1>max1):
    max1 = gcd1
     
# print max1
# as the result
print(max1)

Output:



4

Explanation: For the given array one of the subarrays having maximum gcd is[3, 5] which has gcd 4.

Time Complexity:  O(n * log(min(a, b))), as it iterates through the input list once of size n, and gcd() method takes log(min(a,b)) time. 
Auxiliary Space: O(log(n)), as it uses recursion and the maximum depth of recursion is log(n).

Example 2:




import math
 
# input list
List = [3, 7, 2, 9, 18, 5, 1, 13 ]
 
max1 = 0
for i in range(len(List)-1):
   
  # use math.gcd() function
  gcd1 = math.gcd(List[i], List[i + 1])
  if(gcd1>max1):
    max1 = gcd1
     
# print max1
# as the result
print(max1)

Output:

9

Explanation:
For the given array one of the subarrays having maximum gcd is[4, 5] which has gcd 9.

Time Complexity:  O(n * log(min(a, b))), as it iterates through the input list once of size n, and gcd() method takes log(min(a,b)) time. 
Auxiliary Space: O(log(n)), as it uses recursion and the maximum depth of recursion is log(n).


Article Tags :