Count common factors until we either reach small or count becomes k .
$ count = 1 ; for ( $ i = 2 ; $ i <= $ small ; $ i ++ ) { if ( $ x % $ i == 0 && $ y % $ i == 0 ) $ count ++ ; if ( $ count == $ k ) return $ i ; }