最快的可能算法总和数字N [英] Fastest possible algorithm to sum numbers up to N

查看:215
本文介绍了最快的可能算法总和数字N的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个真正的快速算法或代码在C中执行以下任务:对于任何给定的整数N,将从1到N的所有数字相加,而不假设N是正数。如果 N <$>

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



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


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.

解决方案

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);.

这篇关于最快的可能算法总和数字N的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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