Maximum GCD of all subarrays of length at least 2 | Java 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
import java . util . * ; class GFG { static int gcd ( int a , int b ) { if ( b == 0 ) { return a ; } return gcd ( b , a % b ) ; } static 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 ; } } System . out . print ( maxGCD + "NEW_LINE"); } public static void main ( String [ ] args ) { int arr [ ] = { 3 , 18 , 9 , 9 , 5 , 15 , 8 , 7 , 6 , 9 } ; int n = arr . length ; findMaxGCD ( arr , n ) ; } }