如何从递归函数中完全返回,该函数给出了每个函数结果的累积相加?

How to fully return from recursion function which gives cumulative addition of each function result?

本文关键字:函数 结果 递归函数 返回      更新时间:2023-10-16

我有函数用这个公式计算二项式系数p(n, x) = n!/(n-x)!.x!

由于实现是递归的,我想在结果系数超过 INT_MAX 时停止进一步的函数执行,它应该返回 -1。

但是,递归函数不是从这种情况返回,而是将此返回值视为内部递归函数返回的计算值。

这给出了错误的结果。

如何处理?

#include <iostream>
#include <cstdlib>
int INT_MAX = 100;
using namespace std;
int binomial_function(int n, int k){
int res = -1;
if (n<k || k<0 ){
return -1;
}
if(k == n || k == 0){
return 1;
}
res = binomial_function(n-1,k-1) + binomial_function(n-1,k);
if (res >= INT_MAX){   // checking overflow of res
return -1;
}
return res;
}
int main(int argc, char *argv[]){
int coefficient = 0;
coefficient = binomial_function(10,5); // actual binomial coeficient is 252 which overflows to INT_MAX
cout<<coefficient<<endl;
coefficient = binomial_function(10,6);  // actual binomial coeficient is 210 which overflows to INT_MAX
cout<<coefficient<<endl;
coefficient = binomial_function(10,8);  // actual binomial coeficient is 1 which does overflows to INT_MAX
cout<<coefficient<<endl;
return 0;
}

实际输出为:

-2
83
45

预期产出:

-1   >> this should be result because coefficient exceeds INT_MAX
-1   >> this should be result because coefficient exceeds INT_MAX
45   >> this should be result because coefficient does not exceeds INT_MAX

在执行添加之前,您应该检查返回值是否不是错误。

int res1, res2;
res1 = binomial_function(n-1,k-1);
res2 = binomial_function(n-1,k);
if (res1 < 0 || res2 < 0){   // checking errors of return values
return -1;
}
res = res1 + res2;
if (res >= INT_MAX){   // checking overflow of res
return -1;
}