NYOJ436 sum of all integer numbers

2014-11-24 09:20:57 · 作者: · 浏览: 0

原题链接

这题坑了不少人,要考虑n为负的情况。好在不管它是正是负总归是等差数列吧,这样规律就明显了,直接用(首项 + 末项)* 项数 / 2;

由于n的范围在10000之内,所以不需要考虑溢出的情况。

关键是项数 = 首尾差的绝对值 + 1;


#include 
  
   
#include 
   
     int main(){ int n; while(scanf("%d", &n) == 1) printf("%d\n", (abs(n - 1) + 1) * (1 + n) / 2); return 0; }