Complex Formula Hints

\[B = R \left[ { {1 - (x + 1) (1 + i)^{-(n-x)} } \over { 2i - 1} } \right] \]

Two issues add to the complexity of the solution: The first is the exponent in the numerator, and the second is the two minus operators, one each in the numerator and the denominator.

The Exponent

We can simplify the exponent: -(n-x) = -n+x = x-n. However, I leave it as it appears in the original problem to serve as an example of the minimal use of parentheses when converting formulas to C++ code. The exponentiation operation (i.e., raising a number to a power) has a high precedence, which means that we can focus our attention on just part of the numerator for now:

\[ (x+1)(1+i)^{-(n-x)} \]

We can use the pow function to raise a number to a power. The function requires a base and an exponent: be = pow(b,e). The most challenging aspect of converting the numerator to C++ code is understanding which part is the base and which part is the exponent. The numerator has three main parts that are easier to see if we make three simple substitutions:

Now the numerator becomes: 1 - ab-c. Exponentiation has a higher precedence than multiplication and takes place first: a(bc), which is a * pow(b, -c) in C++ code. Notice that the only parentheses needed are those that form the argument list for the pow function. Although we can program the final solution based on the three substitutions made above, the variables a, b, and c have no real meaning in the context of the problem: the substitutions were just a way of helping us see what to do with the exponent. The full C++ implementation of the numerator is:

1 - (x + 1) * pow(1 + i, -(n - x))

Finally, notice that the comma separating the base and exponent is sufficient to separate the two expressions - additional grouping parentheses are unnecessary. The parentheses in -(n-x) are needed for the unary negation operator, but we can remove them as noted above. While the temporary variables might help us develop a solution, they can make the final C++ more difficult to understand (see Misusing temporary variables), so they should not be in the final solution.

The Minus Operators

\[B = R \left[ { {1 \bbox[5px,border:1px solid red]{-} (x + 1) (1 + i)^{-(n-x)} } \over { 2i \bbox[5px,border:1px solid red]{-} 1} } \right] \]

The long horizontal line is the division operator, which has higher precedence than the two minus operators. When used this way, the division operator acts as a set of grouping parentheses - meaning the formula evaluates the numerator and the denominator before the division operation takes place: (numerator) / (denominator).

Other Considerations