如何以更快的方式找到给定数字的除数之和?

编程入门 行业动态 更新时间:2024-10-24 18:16:46
本文介绍了如何以更快的方式找到给定数字的除数之和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在解决一个问题,找到一个给定数字的除数之和(数字是一个大的),...我写了代码,它超出了时间限制......我可以减少在这种情况下的时间...请帮助我....在初学者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??

更多推荐

如何以更快的方式找到给定数字的除数之和?

本文发布于:2023-11-30 21:29:45,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:除数   之和   更快   方式   数字

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!