The code by Visitor can be simplified further:
const int array_sum( std::accumulate(a, a + array_size, 0) );
int sum( array_sum * array_sum );
for (int i = 0; i < array_size; ++i) {
sum -= a[i] * a[i];
}
And I guess a temporary could be used:
const int array_sum( std::accumulate(a, a + array_size, 0) );
int sum( array_sum * array_sum );
for (int i = 0; i < array_size; ++i) {
const int tmp( a[i] );
sum -= tmp * tmp;
}
And of course the squaring step can also be done using STL:
const int array_sum( std::accumulate(a, a + array_size, 0) );
std::transform( a, a + array_size, a, a, std::multiplies<int>() ); // store in a
const int sum( array_sum * array_sum - std::accumulate(a, a + array_size, 0) );
EDIT: A simple loop with a single pass:
int array_sum( 0 ), square_sum( 0 );
for( int i(0) ; i < array_size; ++i )
{
int tmp(a[i]);
array_sum += tmp;
square_sum += tmp * tmp;
}
const int sum( array_sum * array_sum - square_sum );