Nearest element with at | Javascript program to print nearest element with at least one common prime factor . ; Loop covers the every element of arr [ ] ; Loop that covers from 0 to i - 1 and i + 1 to n - 1 indexes simultaneously ; print position of closest element ; Recursive function to return gcd of a and b ; Driver Code
function nearestGcd ( arr , n ) { for ( let i = 0 ; i < n ; ++ i ) { let closest = - 1 ; for ( let j = i - 1 , k = i + 1 ; j > 0 k <= n ; -- j , ++ k ) { if ( j >= 0 && __gcd ( arr [ i ] , arr [ j ] ) > 1 ) { closest = j + 1 ; break ; } if ( k < n && __gcd ( arr [ i ] , arr [ k ] ) > 1 ) { closest = k + 1 ; break ; } } document . write ( closest + " " ) ; } } function __gcd ( a , b ) { if ( b == 0 ) return a ; return __gcd ( b , a % b ) ; } let arr = [ 2 , 9 , 4 , 3 , 13 ] ; let n = arr . length ; nearestGcd ( arr , n ) ;