Nearest element with at | PHP 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
< ? php function nearestGcd ( $ arr , $ n ) { for ( $ i = 0 ; $ i < $ n ; ++ $ i ) { $ closest = -1 ; for ( $ 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 ; } } echo $ closest . " " ; } } function __gcd ( $ a , $ b ) { if ( $ b == 0 ) return $ a ; return __gcd ( $ b , $ a % $ b ) ; } $ arr = array ( 2 , 9 , 4 , 3 , 13 ) ; $ n = sizeof ( $ arr ) ; nearestGcd ( $ arr , $ n ) ; ? >