Print the kth common factor of two numbers | Java program to find kth common factor of two numbers ; Returns k 'th common factor of x and y. ; Find smaller of two numbers ; Count common factors until we either reach small or count becomes k . ; If we reached small ; Driver code
import java . lang . * ; class GFG { static int findKHCF ( int x , int y , int k ) { int small = Math . min ( x , y ) ; int count = 1 ; for ( int i = 2 ; i <= small ; i ++ ) { if ( x % i == 0 && y % i == 0 ) count ++ ; if ( count == k ) return i ; } return - 1 ; } public static void main ( String [ ] args ) { int x = 4 , y = 24 , k = 3 ; System . out . print ( findKHCF ( x , y , k ) ) ; } }