保存未知数量的整数,而不会花费太多时间/内存

Saving unknown amount of integers without taking too much time/memory

本文关键字:太多 时间 内存 未知数 整数 保存      更新时间:2023-10-16
#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;
}

我正在做一个在线练习,它说第一行可能有 2000000 个案例,所以我做了一个数组,但是,当我提交解决方案时,它超过了时间......所以我想知道什么是替代和更快的方法来做到这一点?该程序现在运行良好,除了它超过了网站的时间限制。

您可以动态分配数组,因此在以下情况下它会更好地工作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;
}

既然你知道数组的大小,请尝试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;
}

我认为你的作业比你想象的要复杂。你的divsum(x( 函数应该返回 x 的所有除数的总和,对吧?在这种情况下,最好对 x 进行因式分解,并使用所有素数(带幂(计算此总和,其乘积等于 x。看看:

http://en.wikipedia.org/wiki/Divisor_function

有一些递归分解的方法 - 例如,如果您已经分解了所有数字直到 n 为止,您可以快速找到 (n + 1( 的因式分解。您还需要生成素数,前 2000000 个数字的 Erathosphene 筛子就可以了。