如何以更快的方式找到给定数字的除数之和? [英] How can i find the sum of divisors of a given number in a faster way?

查看:85
本文介绍了如何以更快的方式找到给定数字的除数之和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在解决一个问题,找到一个给定数字的除数之和(数字是一个大的),...我写了代码,它超出了时间限制......我可以减少在这种情况下的时间...请帮助我....在初学者2编程在c :)

Hre是我的代码:


# include< stdio.h>

int main()

{

long long int k,n,t,sum = 0;

scanf("%lld",& t);

while(t)

{

scanf( "%lld"& n);

for(k = 1; k< n; k ++)

{

if( n%k == 0)

{

sum = sum + k;

}

}

printf("%lld \ n",sum);

t - ;

sum = 0;

}

系统(暂停);

返回0;

}

解决方案
你可以轻松跳过这里有很多数字,你只需要考虑它背后的数学。

想想这个例子:什么是最高的除数我我会找到一个数字(当然不包括数字本身)?

如果你可以在循环之前计算这个数字(或它的近似值),你只需要达到这个数字,而不是一直到给定的数字。

我很确定如果再深入研究一下,你可以找到其他方法加快速度。


PS:如果你在代码标签中发布你的代码(把 [code] 放在代码前面并且 [/ code] 背后),为每个人阅读更容易。可以在此处找到更多发布指南。


请记住,除数成对出现。每当你找到循环的除数时,你就可以找到它的伙伴。然后你的循环只需要找到一半的除数。


@yaarofdoom


谢谢,这是我的第一篇帖子我在论坛上看病了下一次abt它...顺便说一下,我知道如果在循环中用n / 2替换n,我可以切断这个循环......但是它还在消耗更多的时间......我能用更好的算法使用??? .....请帮助


@donbock


谢谢你能为这个1推荐一个更好的算法吗?? / BLOCKQUOTE>

I m solving a problem to find the sum of divisors of a given number(the number is a large one),...i hv written the code bt it''s exceding the time limit...hw can i reduce the time in such cases...pls help me....i m a beginner 2 programming in c :)
Hre is my code:

#include<stdio.h>
int main()
{
long long int k,n,t,sum=0;
scanf("%lld",&t);
while(t)
{
scanf("%lld",&n);
for(k=1;k<n;k++)
{
if(n%k==0)
{
sum=sum+k;
}
}
printf("%lld\n",sum);
t--;
sum=0;
}
system("pause");
return 0;
}

解决方案

There''s a lot of numbers you can easily skip here, you just have to think about the maths behind it.
Think about this for instance: "What''s the highest divisor I''m ever going to find for a number (excluding the number itself of course)?"
If you can calculate this number (or an approximation of it) before the loop, you only have to go up to this number, instead of all the way up to the given number.
I''m sure if you look into it a little bit further you can find other ways to speed it up as well.

PS: If you post your code in code-tags (put [code] in front of your code and [/code] behind it), it is much easier to read for everyone. More posting guidelines can be found here.


Remember that divisors come in pairs. Every time you find a divisor with your loop you can then find its partner. Then your loop only needs to find half the divisors.


@yaarofdoom

Thanks,this was my 1st post i dis forum,ill tk care abt it next time...btw i know i can cutshort this loop if replace n with n/2 in the loop......bt still it''s consuming more time.....ny better algorithm i can use???.....pls help

@donbock

Thanks can u suggest a better algorithm for this 1??


这篇关于如何以更快的方式找到给定数字的除数之和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆