简体   繁体   English

在C ++中调整整数除法的商

[英]Adjusting quotient of integer division in C++

Example: B+ Trees 示例:B +树

Given N tuples in the tree, at most di children per inner node and at most dl values per leaf, the minimum height of a B+ Tree would be h = ceil(log_di((N + dl - 1) / dl)) if I am not mistaken. 给定树中的N个元组,每个内部节点最多di个子节点,每个叶子最多dl值,如果I,则B +树的最小高度为h = ceil(log_di((N + dl - 1) / dl))没错。 This is only true if / denotes the integer division and I could probably replace (N + dl - 1) / dl with static_cast<double>(N) / dl . 仅当/表示整数除法并且我可以用static_cast<double>(N) / dl替换(N + dl - 1) / dl ,这才是正确的。

#include <cmath>
int minHeight(int N)
{
    constexpr int di = 256;
    constexpr int dl = 255;
    return std::lround(std::ceil(log((N + (dl - 1)) / dl) / log(di)));
}

My interest lies in the pattern: (N + d - 1) /d . 我的兴趣在于模式: (N + d - 1) /d This seems to be used when calculating the smallest multiple of the divisor (d) that is greater or equal to the dividend (N). 当计算除数(d)的最小倍数大于或等于被除数(N)时,似乎使用了此方法。

Questions 问题

  1. Does this pattern have any name associated with it? 这个模式有名称吗? How common is it when designing data structures and algorithms? 设计数据结构和算法时有多普遍?
  2. Is there another way to write this code in c++ to be easier to understand, if it is uncommon? 如果不常见,还有另一种方法可以用c ++编写以使其更容易理解吗?

(N + d - 1) / d is a perfectly normal way of writing an integer expression in C++. (N + d - 1) / d是在C ++中编写整数表达式的一种完全正常的方法。 All of the terms in this expression are of integer type so, in particular, both numerator and denominator of the division / are also int . 此表达式中的所有术语均为整数类型,因此,尤其是/分子和分母也均为int Therefore, C++ will apply / as the division operator on int types. 因此,C ++将/作为int类型的除法运算符。

I'm not entirely sure exactly what you're asking in either of your questions. 我不确定您在这两个问题中到底要问什么。 This "pattern" doesn't have a particular name that I'm aware of, but I'm not sure why you think it should have one. 这个“模式”没有我知道的特定名称,但是我不确定您为什么认为应该有一个特定的名称。 It's simply a mathematical expression. 这只是一个数学表达式。

As for making it "easier to understand", that is of course subjective, but (aside from the fact that variables don't have informative names) I find it perfectly readable. 至于使其“更易于理解”,这当然是主观的,但是(除了变量没有参考性的名称这一事实),我发现它完全可读。 If you're looking for an algebraic simplification of the expression, then I'd warn you against it. 如果您正在寻找表达式的代数简化形式,那么我警告您。 While (N/d) + (1/d) - 1 , for example, looks mathematically equivalent it is not in this case in general. 例如,虽然(N/d) + (1/d) - 1在数学上看起来是等效的,但通常在这种情况下不是这样。 This is mainly because of the aforementioned fact that these are integer divisions, but also because the int type has finite precision which may affect the result in some cases (with integer overflow, for example). 这主要是由于上述事实,即它们是整数除法,而且还因为int类型具有有限的精度,这在某些情况下可能会影响结果(例如,整数溢出)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM