Program for average of an array without running into overflow
Last Updated :
30 Jun, 2022
Given an array arr[] of size N, the task is to find the average of the array elements without running into overflow.
Examples:
Input: arr[] = { INT_MAX, INT_MAX }
Output:
Average by Standard method: -1.0000000000
Average by Efficient method: 2147483647.0000000000
Explanation:
The average of the two numbers by standard method is (sum / 2).
Since the sum of the two numbers exceed INT_MAX, the obtained output by standard method is incorrect.
Input: arr[] = { INT_MAX, 1, 2 }
Output:
Average by Standard method: -715827882.0000000000
Average by Efficient method: 715827883.3333332539
Approach: The given problem can be solved based on the following observations:
- The average of N array elements can be obtained by dividing the sum of the array elements by N. But, calculating sum of the array arr[] may lead to integer overflow, if the array contains large integers.
- Therefore, average of the array can be calculated efficiently by the following steps:
- Traverse the array, using a variable i over the range of indices [0, N – 1]
- Update avg = (avg+ (arr[i] – avg)/(i+1))
Follow the steps below to solve the problem:
- Initialize two variables, say sum as 0 and avg as 0, to store the sum and average of the array elements respectively.
- Traverse the array arr[], update avg = avg + (arr[i] – avg) / (i + 1) and update sum = sum + arr[i].
- After completing the above steps, print the average by the standard method, i.e. sum / N and print the average by the efficient method, i.e. avg
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
double average( int arr[], int N)
{
int sum = 0;
for ( int i = 0; i < N; i++)
sum += arr[i];
return ( double )sum / N;
}
double mean( int arr[], int N)
{
double avg = 0;
for ( int i = 0; i < N; i++) {
avg += (arr[i] - avg) / (i + 1);
}
return avg;
}
int main()
{
int arr[] = { INT_MAX, 1, 2 };
int N = sizeof (arr) / sizeof (arr[0]);
cout << "Average by Standard method: " << fixed
<< setprecision(10) << average(arr, N) << endl;
cout << "Average by Efficient method: " << fixed
<< setprecision(10) << mean(arr, N) << endl;
return 0;
}
|
Java
import java.util.*;
class GFG{
static Double average( int arr[], int N)
{
int sum = 0 ;
for ( int i = 0 ; i < N; i++)
sum += arr[i];
return Double.valueOf(sum / N);
}
static Double mean( int arr[], int N)
{
Double avg = 0.0 ;
for ( int i = 0 ; i < N; i++)
{
avg += Double.valueOf((arr[i] - avg) / (i + 1 ));
}
return avg;
}
public static void main(String args[])
{
int arr[] = {Integer.MAX_VALUE, 1 , 2 };
int N = arr.length;
System.out.println( "Average by Standard method: " + String.format( "%.10f" , average(arr, N)));
System.out.println( "Average by Efficient method: " + String.format( "%.10f" , mean(arr, N)));
}
}
|
Python3
import sys
def average(arr, N):
sum = 0
for i in range (N):
sum + = arr[i]
return sum / / N * 1.0 - 1
def mean(arr, N):
avg = 0
for i in range (N):
avg + = (arr[i] - avg) / (i + 1 )
return round (avg, 7 )
if __name__ = = '__main__' :
arr = [ 2147483647 , 1 , 2 ]
N = len (arr)
print ( "Average by Standard method: " , "{:.10f}" . format (
- 1.0 * average(arr, N)))
print ( "Average by Efficient method: " , "{:.10f}" . format (
mean(arr, N)))
|
C#
using System;
class GFG{
static double average( int [] arr, int N)
{
int sum = 0;
for ( int i = 0; i < N; i++)
sum += arr[i];
return ( double )(sum / N);
}
static double mean( int [] arr, int N)
{
double avg = 0.0;
for ( int i = 0; i < N; i++)
{
avg += (( double )((arr[i] - avg) / (i + 1)));
}
return avg;
}
static public void Main()
{
int [] arr = { Int32.MaxValue, 1, 2 };
int N = arr.Length;
Console.WriteLine( "Average by Standard method: " +
(average(arr, N)).ToString( "F10" ));
Console.WriteLine( "Average by Efficient method: " +
(mean(arr, N)).ToString( "F10" ));
}
}
|
Javascript
<script>
function average(arr, N)
{
var sum = 0;
for ( var i = 0; i < N; i++)
sum += arr[i];
if (sum>2147483647)
{
sum = -2147483647 + (sum - 2147483649)
}
return parseInt(sum / N);
}
function mean(arr, N)
{
var avg = 0;
for ( var i = 0; i < N; i++) {
avg += parseFloat((arr[i] - avg) / (i + 1));
}
return avg;
}
var arr = [2147483647, 1, 2 ];
var N = arr.length
document.write( "Average by Standard method: " + average(arr, N).toFixed(10) + "<br>" );
document.write( "Average by Efficient method: " + mean(arr, N).toFixed(10)+ "<br>" );
</script>
|
Output:
Average by Standard method: -715827882.0000000000
Average by Efficient method: 715827883.3333332539
Time Complexity: O(N)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...