Find the maximum GCD possible for some pair in a given range [ L , R ] | Java program for the above approach ; Function to calculate GCD ; Function to calculate maximum GCD in a range ; Variable to store the answer ; If Z has two multiples in [ L , R ] ; Update ans ; Return the value ; Driver code ; Input ; Function Call
import java . io . * ; class GFG { public static int GCD ( int a , int b ) { if ( b == 0 ) return a ; return GCD ( b , a % b ) ; } public static int maxGCDInRange ( int L , int R ) { int ans = 1 ; for ( int Z = R ; Z >= 1 ; Z -- ) { if ( ( R / Z ) - ( L - 1 ) / Z > 1 ) { ans = Z ; break ; } } return ans ; } public static void main ( String [ ] args ) { int L = 102 ; int R = 139 ; System . out . println ( maxGCDInRange ( L , R ) ) ; }