Maximum GCD among all pairs ( i , j ) of first N natural numbers | Java program for the above approach ; Function to find maximum gcd of all pairs possible from first n natural numbers ; Stores maximum gcd ; Iterate over all possible pairs ; Update maximum GCD ; Driver Code
import java . util . * ; class GFG { static int maxGCD ( int n ) { int maxHcf = Integer . MIN_VALUE ; for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = i + 1 ; j <= n ; j ++ ) { maxHcf = Math . max ( maxHcf , __gcd ( i , j ) ) ; } } return maxHcf ; } static int __gcd ( int a , int b ) { return b == 0 ? a : __gcd ( b , a % b ) ; } public static void main ( String [ ] args ) { int n = 4 ; System . out . print ( maxGCD ( n ) ) ; } }