Large Arithmetic by MinGW fails

138 Views Asked by At

My general task is to compute the sum of a set of positive integers, each multiplied by descending powers of 36, with the first power being the size of the set - 1According to Wolfram,
LaTeX for https://www.wolframalpha.com/input/?i=9*36%5E6%2B13*36%5E5%2B19*36%5E4%2B6*36%5E3%2B7*36%5E2%2B8*36%2B2

I expected the following to return the same:

#include <iostream>
#include <vector>
#include <math.h>

unsigned long long f(const std::vector<unsigned> &coefficients)
{
    unsigned short exponent = coefficients.size() - 1;
    unsigned long long sum;
    for (unsigned i : coefficients)
    {
        sum += i * pow(36, exponent);
        --exponent;
    }
    return sum;
}

int main()
{
    std::cout << f({9,13,19,6,7,8,2});
}

but instead it returns 20416905041. The minimum capacity of an unsigned long long integer is 0 to 18446744073709551615, according to Alex B on this question, so capacity doesn't appear to be the problem.


Specifications:

  • Compiler: x86_64-w64-mingw32 from the Windows TDM-GCC Compiler Suite
  • Compiled via g++ mwe.cpp -std=c++11 -omwe
  • OS: Windows 10 Home
1

There are 1 best solutions below

0
On BEST ANSWER

From M.M's comment on the question:

pow is a floating point function and therefore will be susceptible to rounding errors. You should use integer variables (do repeated multiplication by 36) instead.