保存未知数量的整数而不占用太多时间/内存

时间:2013-11-20 19:52:09

标签: c++ arrays memory

#include <iostream>

using namespace std;

unsigned long long divsum(unsigned long long x);

int main()
{
    unsigned long long x;
    cin >> x;
    unsigned long long y[200000];
    for (unsigned int i = 0; i < x; i++)
        cin >> y[i];
    for (unsigned int i = 0; i < x; i++){
        cout << divsum(y[i]) << endl;
    }
    return 0;
}

unsigned long long divsum(unsigned long long x){
    int sum = 0;
    for(unsigned int i = 1; i <= x/2; i++){
        if(x % i == 0)
            sum += i;
    }
    return sum;
}

我正在进行在线练习,它说第一行可能有200万个案例,所以我制作了一个数量的数组,但是,当我提交解决方案时,它超过了时间..所以我想知道是什么这是另一种更快速的方法吗?该程序目前正常,但超出了网站的时间限制。

2 个答案:

答案 0 :(得分:0)

由于您知道数组的大小,请尝试vectorreserve

 int main()
    {
        unsigned long long x;
        cin >> x;
         unsigned long long var;
         vector<unsigned long long> y;
         y.reserve(x);
         for (unsigned int i = 0; i < x; i++){
          cin >> y[i];
         }for (unsigned int i = 0; i < x; i++){
           cout << divsum(var) << endl;
        }
        return 0;
    }

交易const &

const unsigned long long & divsum(const unsigned long long & x){
    int sum = 0;
    unsigned long long x2 = x/2
    for(unsigned int i = 1; i <= x2; i++){
        if(x % i == 0)
            sum += i;
    }
    return sum;
}

答案 1 :(得分:0)

您可以动态分配数组,以便在x < 200000

的情况下更好地工作
int main()
{
    unsigned long long x;
    cin >> x;
    unsigned long long *y = new unsigned long long[x];
    // you can check if new didn't throw an exception here
    for (unsigned int i = 0; i < x; i++)
        cin >> y[i];
    for (unsigned int i = 0; i < x; i++){
        cout << divsum(y[i]) << endl;
    }
    delete[] y;
    return 0;
}