Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The program gives wrong answer for large input

Tags:

arrays

c

sum

I am trying to solve this problem:

Given five positive integers, find the minimum and maximum values that can be calculated by summing exactly four of the five integers. Then print the respective minimum and maximum values as a single line of two space-separated long integers. (the input are the five elements of the array arr)

void miniMaxSum(int arr_count, int *arr) 
{ 
    unsigned long int sum1, sum2, sum3, sum4, sum5, max, min;
    int i;
    sum1 = arr[0] + arr[1] + arr[2] + arr[3];
    sum2 = arr[4] + arr[1] + arr[2] + arr[3];
    sum3 = arr[0] + arr[4] + arr[2] + arr[3];
    sum4 = arr[0] + arr[1] + arr[4] + arr[3];
    sum5 = arr[0] + arr[1] + arr[2] + arr[4];
    min = max = sum1;
    unsigned long int sumall[5] = { sum1, sum2, sum3, sum4, sum5 };
    for (i = 0; i < arr_count; i++) {
        if (sumall[i] >= max) {
            max = sumall[i];
        } else if (sumall[i] <= min) {
            min = sumall[i];
        }
    }
    printf("%lu %lu", min, max);
}

the above function gives output

2063136757 18446744072159051663

for the input

256741038 623958417 467905213 714532089 938071624
like image 354
Yash Kasle Avatar asked Oct 20 '25 19:10

Yash Kasle


1 Answers

Instead of int addition which risks signed integer overflow (undefined behavior (UB)), perform wider addition.

void miniMaxSum(int arr_count, int* arr) { 
  unsigned long int sum1, sum2, sum3, sum4, sum5, max, min;
  ...
  sum1=arr[0]+arr[1]+arr[2]+arr[3];
  //   ^ int addition w/int sum  ^

  sum1 = 0UL + arr[0] + arr[1] + arr[2] + arr[3];
  //     ^ unsigned long addition with unsigned long sum ^

Even better, as long may not be wider, use long long and stay with signed types:

  long long sum1 = 0LL + arr[0] + arr[1] + arr[2] + arr[3];
  //               ^ long long addition w/long long sum  ^
  ...
  printf("%lld %lld",min,max);

Curious way to find min/max

OP's min/max search loop the finds the man/max of the 5 sums. Notice the max exceeds INT_MAX for OP.

2,063,136,757
2,744,467,343

The sum of all 5 minus max sum in then the the min value of the 5 original.
The sum of all 5 minus min sum in then the the max value of the 5 original.

938,071,624
256,741,038

like image 183
chux - Reinstate Monica Avatar answered Oct 22 '25 10:10

chux - Reinstate Monica