Nearest element with at | C ++ 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 ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void nearestGcd ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; ++ i ) { int closest = -1 ; for ( int 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 ; } } cout << closest << " ▁ " ; } } int main ( ) { int arr [ ] = { 2 , 9 , 4 , 3 , 13 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; nearestGcd ( arr , n ) ; return 0 ; }