UPDATE:
Thanks for the helpful comments and tips. Using what you guys said is what I came 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 have another question. In the above code, when I catch an integer overflow, I don't return a value - it's just return; .
One of the comments below suggested return -1; however this would not work, considering that -1 is still a real integer, right?
I am not sure what to do, since the return type is int for my function. Does return; or is there a better way to do this? It was also suggested exit(1); , but does it exit the entire program or just functions?
ORIGINAL:
Your function should use integer arithmetic to ensure that the results are accurate and also detect any integer overflows caused by exceeding the maximum allowed values.
I am trying to catch integer overflow while calculating binomial coefficients. Although a simple concept, what throws me away is that it is not just a one-time addition, it is a recursive algorithm that constantly executes amounts.
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 } }
Within this logic, I assume that the catch should be in a recursive call. Sort of:
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)