um ... how about just calculating the average and then rounding to the integer? round(mean(thearray)) Most languages have tools that allow you to specify a rounding method.
EDIT: So it turns out that this question really is to avoid overflow, not rounding. Let me make it clear that I agree with those who said (in the comments) that in practice there is nothing to worry about, since this happens so rarely, and when this happens, you can always avoid using a larger data type.
I see that several other people gave answers, which basically consist of dividing each number in the array by the number of arrays, and then adding them. This is also a good approach. But only for kicks, here's an alternative (in the C-ish pseudo-code):
int sum_offset = 0; for (int i = 1; i < length(array); i++) sum_offset += array[i] - array[i-1];
Or another way to do the same:
int min = INT_MAX, max = INT_MIN; for (int i = 0; i < length(array); i++) { if (array[i] < min) min = array[i]; if (array[i] > max) max = array[i]; } int sum_offset = max - min;
Of course, you need to make sure that sum_offset does not overflow, which can happen if the difference between the largest and smallest elements of the array is greater than INT_MAX. In this case, replace the last four lines with approximately the following:
// round by your method of choice int mean_offset = round((float)max / length(array) - (float)min / length(array)); int mean = mean_offset + min;
General information: this method or something like that works well for the mental calculation of the average array, the elements of which are grouped close to each other.
source share