有什么方法可以减少这个代码的执行时间吗

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

本文关键字:代码 执行时间 方法 什么      更新时间:2023-10-16

我正试图找到给定数字的所有除数的和但是我已经超过了时间限制,请帮我减少这个代码的时间限制。

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;
    }

}