HDOJ--1001Sum Problem

原题链接


Problem Description
Hey, welcome to HDOJ(Hangzhou Dianzi University Online Judge).

In this problem, your task is to calculate SUM(n) = 1 + 2 + 3 + ... + n.
 

Input
The input will consist of a series of integers n, one integer per line.
 

Output
For each case, output SUM(n) in one line, followed by a blank line. You may assume the result will be in the range of 32-bit signed integer.
 

Sample Input
 
  
1 100
 

Sample Output
 
  
1 5050
 

思路:简单的算术求和

1.使用for循环相加
#include<stdio.h>
 
 int main()
 {
 	int i,n,sum;
 	while(scanf("%d",&n)!=EOF)
 	{
 		sum=0;
 		for(i=1;i<=n;i++)
 			sum+=i;
 		printf("%d\n\n",sum);
	 }
 	return 0;
 }


PS:使用公式求和会造成数据溢出,不能AC,


在这里a1+an=1+n,只需要将n或1+n能除以2的先除,然后再相乘即可

猜你喜欢

转载自blog.csdn.net/y_cnew/article/details/79828303
今日推荐