简体   繁体   English

有什么方法可以减少此代码的执行时间?

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

I am trying to find the sum of all the divisors of a given number But I am exceeding the time limit,help me to reduce the time limit 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

I would say go up to sqrt(a). 我会说上sqrt(a)。 Each time you have a remainder 0, add both the i and a/i. 每次余数为0时,都将i和a / i相加。 You will need to take care of the corner cases, but this should bring down the time complexity. 您将需要处理一些特殊情况,但这会降低时间的复杂性。 Depending on how large a is this should be faster. 根据a的大小,它应该更快。 For small values this may actually be slower. 对于较小的值,实际上可能会更慢。

This problem can be optimized by prime factorization . 这个问题可以通过素数分解来优化。

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 

Thanks everyone for the help..I got the answer 谢谢大家的帮助。

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


}

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

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