有什么办法可以减少这段代码的执行时间吗?

Is there any way to reduce execution time of this code?

我正在尝试求出给定数字的所有除数之和 但是我超过了时间限制,帮我减少这段代码的时间限制。

int a,count=0;
cin>>a;
for(int i=2;i<=a/2;i++) {
    if(a%i==0) {
        count=count+i;
    }
}
count++;
cout<<count;

如果您同时对两个除数求和,则可以进行循环 运行 sqrt(a),而不是 a / 2count += i + a / i

我会说上升到 sqrt(a)。每次余数为 0 时,将 i 和 a/i 相加。您将需要处理极端情况,但这应该会降低时间复杂度。根据 a 的大小,这应该更快。对于较小的值,这实际上可能会更慢。

这个问题可以通过质因数分解来优化。

Let’s assume any number’s prime factor is = a ^n*b^m*c^k
Then, Total number of devisors will be = (n+1)(m+1)(k+1)
And sum of divisors = (a^(n+1) -1 )/(a-1)  *  (b^(m+1)-1)/(b-1) *(c^(k+1)-1)/(c-1)
X = 10 = 2^1 * 5^1
Total number of devisors = (1+1)(1+1) =2*2= 4
Sum of divisors  = (2^2 – 1 ) /1 * (5^2 -1 )/4 =  3 * 24/4  =  18
1+2+5+10 = 18 

谢谢大家的帮助..我得到了答案

     bool  is_perfect_square(int n) 
     {
     if (n < 0)
     return false;
     int root(round(sqrt(n)));
     return n == root * root;
     }
     main()
     {
     int t;
     cin>>t;
     while(t--)
    {
    int a,count=0;
    cin>>a;
    bool c=is_perfect_square(a);


    for(int i=2;i<=sqrt(a);i++)
    {
        if(a%i==0)
        {
            count=count+i+a/i;

        }

    }
    if(c==true)
    {
                count = count - sqrt(a);
    }
    count++;
    cout<<count<<endl;
    }


}