题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1001
题目大意:输入一个数n,输出1+2+3+...+n。
题目思路:有两个思路,第1个思路是直接用求和公式n*(n+1)/2,注意一点,题中说结果不会超过32位有符号整型数,但是n*(n+1)有可能超过这个范围,所以在使用的时候要有一个判断,或者是采用更大范围的数据类型;第2个思路就是用循环从1加到n,不必担心计算过程中的溢出问题。
AC代码:
// HDOJ
// 1001.cpp
/*
ID: Firwaless
LANG: C++
TASK: Sum Problem
*/
#include <cstdio>
int main()
{
int n, ans;
while (~scanf("%d", &n))
{
if (n & 1)
{
ans = (n + 1) / 2 * n;
}
else
{
ans = n / 2 * (n + 1);
}
printf("%d\n\n", ans);
}
return 0;
}