Store the difference between the prime and the array element
int minm = abs ( primes [ x ] - arr [ i ] ) ; if ( x > 1 ) { minm = min ( minm , abs ( primes [ x - 1 ] - arr [ i ] ) ) ; } ans += minm ; } return ans ; }