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?
My guess would be unsigned integer overflow.
i
increases until it is >c
, butc
is a double whereasi
is an unsigned int. It reaches the maximum (UINT_MAX
) and wraps to 0 before it reaches the value ofc
.I.e. 1287644555 is less than
UINT_MAX
, so it completes. But 3560664427 is greater thanUINT_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.