简体   繁体   English

大数除法

[英]Division of very large numbers

I have written following code in C++: 我用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. 当输入此代码的输入为“ 728 1287644555”时,大约需要5秒钟来计算答案,但是当输入大约为三倍时,即“ 763 3560664427”,则给出的时间就不会很长。(我等待了大约半小时)可以看出,算法是线性顺序的。 Therefore, it should take roughly 15 seconds. 因此,大约需要15秒。 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. i增加直到> c ,但是c是双精度数,而i是无符号整数。 It reaches the maximum ( UINT_MAX ) and wraps to 0 before it reaches the value of c . 它达到最大值( UINT_MAX )并在达到c值之前包装为0。

Ie 1287644555 is less than UINT_MAX , so it completes. 即1287644555小于UINT_MAX ,因此完成。 But 3560664427 is greater than UINT_MAX , so it loops forever. 但是3560664427大于UINT_MAX ,因此它将永远循环。 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. 在我自己的机器上( UINT_MAX = 4294967295),第一个输入需要16秒的处理时间,而第二个输入需要43.5秒的处理时间,这几乎是您期望的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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