Search code examples
c++mathinteger-overflowarithmetic-expressionsinteger-arithmetic

How to avoid integer overflow in case of pow function in division with a number?


I have the following statement.

d = (pow(a,2*l+1)+1)/(val+1);  

Here,

  • val, a and l are variables which are of no relation to the question.
  • the numerator can exceed long long int range.
  • denominator is a divisor of the numerator.

But the final answer d will surely be under the long long int range. How to calculate d without loss of accuracy? I would prefer an answer without converting them to array and using grade school multiplication and division.


Solution

  • I don't have time to write a proper answer now; I'll expand this later if I get a chance. The basic idea is to use the grade-school algorithm, working with "digits" that are a power of the denominator. Do a Google search for "Schrage multiplication" or look here for references.