It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center




已关闭8年。




我想要一个真正的快速算法或C中的代码来完成以下任务:对于任何给定的整数N,将1到N的所有数字相加,而不假定N为正。我做了一个从1到N的循环,但这太慢了。

最佳答案

如果N为正:int sum = N*(N+1)/2;
如果N为负:int tempN = -N; int sum = 1 + tempN*(tempN+1)/2 * (-1);

关于c++ - 最快的算法求和最多N个数字,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2624387/

10-12 07:34
查看更多