将 N 以内的数字相加的最快算法
我想要一个真正快速的 C 算法或代码来完成以下任务:对于任何给定的整数 N,对从 1 到 N 的所有数字求和,而不假设 N 为正数。我做了一个从 1 到 N 求和的循环,但是太慢了。
I want a really fast algorithm or code in C to do the following task: sum all numbers from 1 to N for any given integer N, without assuming N is positive. I made a loop summing from 1 to N, but it is too slow.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
如果
N
为正数:int sum = N*(N+1)/2;
如果
N
为负数:int tempN = -N; int sum = 1 + tempN*(tempN+1)/2 * (-1);
。If
N
is positive:int sum = N*(N+1)/2;
If
N
is negative:int tempN = -N; int sum = 1 + tempN*(tempN+1)/2 * (-1);
.您正在寻找的公式是在您的问题的多个答案中发布的公式的更通用形式,这是一个 算术级数/级数,差异因子为1。来自维基百科,如下:
只要 m 始终小于 n,上述公式就会处理负数。例如,要获得从 1 到 -2 的总和,请将 m 设置为 -2,将 n 设置为 1,即从 -2 到 1 的总和。这样做会导致:
这是预期的结果。
The formula you're looking for is a more general form of the one posted in multiple answers to your question, which is an Arithmetic Series/Progression with a difference factor of 1. From Wikipedia, it is the following:
The above formula will handle negative numbers as long as m is always less than n. For example to get the sum from 1 to -2, set m to -2 and n to 1, i.e. the sum from -2 to 1. Doing so results in:
which is the expected result.
为了完成上述答案,这就是证明公式的方法(正整数的示例,但原理与负数或 Void 指出的任何算术套件相同)。
只需将套件写两次,如下所示并添加数字:
Just to complete the above answers, this is how you prove the formula (sample for positive integer but principle is the same for negatives or any arithmetic suite as Void pointed out).
Just write the suite two times as below and add numbers:
为了处理整数溢出,我将使用以下函数:
To deal with integer overflow I'd use the following function:
试试这个...
其中 n 是您需要求和的最大整数。
总和为 (n*(N+1))/2
Try this...
Where n is the maximum integer you need to sum to.
The sum is (n*(N+1))/2
int sum(int n) {
返回 (n < 0 ? n *(-n + 1) / 2 + 1 : n * ( n + 1) / 2);
}
int sum(int n) {
return (n < 0 ? n *(-n + 1) / 2 + 1 : n * ( n + 1) / 2);
}
你听说过顺序和顺序吗?系列 ?你想要的“快速”代码是从 1 到 N 的算术级数之和..谷歌它..事实上打开你的数学书..
have you heard about sequence & series ? The 'fast' code that you want is that of sum of arithmetic series from 1 to N .. google it .. infact open your mathematics book..
如果|n|足够小,查找表将是最快的。
或者使用缓存,首先查找缓存,如果找不到记录则使用n * (n + 1) / 2(如果n为正数)计算总和,并将结果记录到缓存中。
if |n| is small enough, a lookup table will be the fastest one.
or using a cache, first search the cache, if can't find the record then caculate the sum by using n * (n + 1) / 2(if n is positive), and record the result into the cache.