简体   繁体   中英

Division of very large numbers

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 ie "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?

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 .

Ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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