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