有什么方法可以减少这个代码的执行时间吗
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 / 2
:count += 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;
}
}
相关文章:
- 需要减少我的C++代码的执行时间
- 视觉在C 中获取每行代码的执行时间
- 测量执行时间 - 在程序代码或外壳中
- 第一次在 Linux 上执行 c++ 代码的时间非常慢
- 最佳C 11测量嵌入式系统代码执行时间的方法
- 两个代码段之间执行时间的奇怪差异
- 预先设置c++代码的执行时间
- 为什么要在我的OpenMP代码中增加执行时间
- 如何减少以下代码的执行时间
- 执行代码的时间百分比为x
- 2个代码的执行时间的数目将不同
- 在 OpenMP 代码C++测量执行时间
- 如何减少以下代码的C++执行时间
- 当我从Java代码执行C++程序时,我应该如何测量它的执行时间
- C++和Haskell代码在不同机器上的执行时间不同
- 有什么方法可以减少这个代码的执行时间吗
- 英特尔TBB代码有不同的执行时间在windows和linux
- 如何获得一个c++代码段执行时间的客观评价
- 如何在c++中获得一段代码的执行时间
- Linux中的代码执行时间