UPDATE:
Thank you for the helpful comments and advice. Using what you guys said, this is what I've come up with:
#include <limits.h>
...
else {
int a = binom(n - 1, k - 1);
int b = binom(n - 1, k);
if(a > 0) {
if (b > INT_MAX - a) { // case 1: integer overflow
printf("int overflow\n");
return;
}
}
else if (b < INT_MIN - a) { // case 2: integer overflow
printf("int overflow\n");
return;
}
int c = a + b;
return c;
}
I do have another question. In the above code, when I catch the integer overflow I am not returning a value -- it is simply return;
.
One of the comments below suggested return -1;
, however this wouldn't work work considering -1 is still a valid integer, correct?
I am not sure what to do since the return type is int
for my function. Does return;
work or is there a better way to do it? Also suggested was exit(1);
, but does that exit the entire program or just the function?
ORIGINAL:
Your function should use integer arithmetic to make sure that the results are exact and also detect any integer overflows caused by exceeding the maximum allowed values.
I am trying to catch an integer overflow when computing binomial coefficients. While a simple concept, what is throwing me off is that this isn't just a one-off addition, it's a recursive algorithm that is constantly performing sums.
This is the function:
// recursive function to calculate binomial coefficients
int binom(int n, int k){
if(k == 0){ // base case
return 1;
}
else if (n == 0){
return 0;
}
else{
return binom(n - 1, k - 1) + binom(n - 1, k); // recursive call
}
}
Under that logic, I assume the catch should be in the recursive call statement. Something like :
if(binom(n-1, k-1) + binom(n-1,k)) causes overflow, return error, else proceed with binom(n-1, k-1) + binom(n-1,k)