NYOJ436 sum of all integer numbers
这题坑了不少人,要考虑n为负的情况。好在不管它是正是负总归是等差数列吧,这样规律就明显了,直接用(首项 + 末项)* 项数 / 2;
由于n的范围在10000之内,所以不需要考虑溢出的情况。
关键是项数 = 首尾差的绝对值 + 1;
#include <cstdio> #include <cstdlib> int main(){ int n; while(scanf("%d", &n) == 1) printf("%d\n", (abs(n - 1) + 1) * (1 + n) / 2); return 0; }