Length of longest subarray of length at least 2 with maximum GCD | Function to calculate GCD of two numbers ; Function to find maximum size subarray having maximum GCD ; Base case ; Let the maximum GCD be 1 initially ; Loop through array to find maximum GCD of subarray with size 2 ; Traverse the array ; Is a multiple of k , increase cnt ; Else update maximum length with consecutive element divisible by k Set cnt to 0 ; Update the maxLength ; Return the maxLength ; Driver Code ; Function call
def gcd ( a , b ) : NEW_LINE INDENT if b == 0 : NEW_LINE INDENT return a NEW_LINE DEDENT return gcd ( b , a % b ) NEW_LINE DEDENT def maxGcdSubarray ( arr , n ) : NEW_LINE INDENT if n == 1 : NEW_LINE INDENT return 0 NEW_LINE DEDENT k = 1 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT k = max ( k , gcd ( arr [ i ] , arr [ i - 1 ] ) ) NEW_LINE DEDENT cnt = 0 NEW_LINE maxLength = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if arr [ i ] % k == 0 : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT else : NEW_LINE INDENT maxLength = max ( maxLength , cnt ) NEW_LINE cnt = 0 NEW_LINE DEDENT DEDENT maxLength = max ( maxLength , cnt ) NEW_LINE return maxLength NEW_LINE DEDENT arr = [ 18 , 3 , 6 , 9 ] NEW_LINE n = len ( arr ) NEW_LINE print ( maxGcdSubarray ( arr , n ) ) NEW_LINE