Division of very large numbers

205 views Asked by At

I have written following code in C++:

#include <cmath>
#include <iostream>

using namespace std;

int main()
{
    double sum, containers, n ,c, max_cap, temp;

    unsigned int j = 1;
       cin >> n >> c;
       sum = containers = n;


       for (unsigned int i = 2 ; i <= c; ++i)
       {
           max_cap = i * n;

           if (max_cap - sum > 0)
           {
              temp = ceil((max_cap - sum)/i);
              containers += temp;
              sum += i * temp;
           }
       }

       cout << containers << '\n';
}

When the input given to this code is "728 1287644555" it takes about 5 seconds to compute the answer but when the input is roughly three times i.e. "763 3560664427" it is not giving a long time.(I waited for around half hour) As it can be seen the algo is of linear order. Therefore, it should take roughly 15 seconds. Why is this happening? Is it because the input is too large in second case? If yes then how is it affecting time so much?

1

There are 1 answers

0
davmac On

My guess would be unsigned integer overflow.

       for (unsigned int i = 2 ; i <= c; ++i)

i increases until it is > c, but c is a double whereas i is an unsigned int. It reaches the maximum (UINT_MAX) and wraps to 0 before it reaches the value of c.

I.e. 1287644555 is less than UINT_MAX, so it completes. But 3560664427 is greater than UINT_MAX, so it loops forever. Which only raises the question of what strange architecture you are running this on :)

On my own machine (UINT_MAX = 4294967295) the first input takes 16 seconds to process while the second takes 43.5 seconds, pretty much what you'd expect.