动态的Java整数/长溢出检查与性能
这是一个相当理论性的问题,因此,尽管语言是专门的Java,任何通用的解决方案就足够了。
This is a rather theoretical question, so while the language is specifically Java, any general solution will suffice.
假设我想写一个平凡的阶乘函数:
Suppose I wanted to write a trivial factorial function:
long factorial(int n)
{
//handle special cases like negatives, etc.
long p = 1;
for(int i = 1; i <= n; i++)
{
p = p * n;
}
return p;
}
但现在,我也想检查阶乘溢出(不只是硬编码一个MAX_FACTORIAL_PARAMETER或东西等)。一般检查乘法期间溢出很简单,只要检查结果,对原来的输入,但在这种情况下,由于溢出可能发生在任何一点上,这将是相当昂贵的,以在每一个循环进行以上的分部和比较
But now, I also want to check if the factorial overflows (without simply hard coding a MAX_FACTORIAL_PARAMETER or something of the like). In general checking for overflow during multiplication is as simple as checking the result against the original inputs, but in this case, since overflow can occur at any point, it would be rather expensive to perform more divisions and comparisons in every single loop.
接下来的问题,是双重的 - 有什么办法来解决溢出的阶乘问题,不检查乘法溢出的每一步或硬编码的最大允许参数
The question then, is twofold--is there any way to solve the factorial problem of overflow without checking for multiplication overflow at every step or hard coding a maximum allowed parameter?
而在一般情况下,我应该怎么办法涉及循环/递归的许多阶段,可以在每一个阶段静默失败,而不通过引入昂贵的层层把关影响性能的问题?
And in general, how should I approach problems that involve many stages of iteration/recursion that could silently fail at every stage without compromising performance by introducing expensive checks at each?