Given two numbers, a and b. Compute the average of the two numbers.
The well know formula (a + b) / 2 may fail at the following case :
If, a = b = (2^31) – 1; i.e. INT_MAX.
Now, (a+b) will cause overflow and hence formula (a + b) / 2 wont work
Improved Formula that does not cause overflow :
Average = (a / 2) + (b / 2) + (((a % 2) + (b % 2)) / 2)
Below is the implementation :
// C code to compute average of two numbers
#include <stdio.h>
#define INT_MAX 2147483647
// Function to compute average of two numbers
int compute_average(int a, int b)
{
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
int main()
{
// Assigning maximum integer value
int a = INT_MAX, b = INT_MAX;
// Average of two equal numbers is the same number
printf("Actual average : %d\n",INT_MAX);
// Function to get the average of 2 numbers
printf("Computed average : %d",compute_average(a, b));
return 0;
}
Output:
Actual average: 2147483647
Computed average: 2147483647
0 comments:
Post a Comment