HDU.1001 Sum Problem

原题

HDU.1001 Sum Problem

分类

杂题

题意

计算从1到正整数n的累加和。

输入/输出 要求与格式
输入内容 每行输入一个正整数
输出结果 结果为累加和
输出格式 每个输出结果独占一行,每个输出结果后接一个空行

题解

这道题说明了是32位整数,使用long long数据类型绰绰有余。

计算的方法也很简单,套用等差数列求和公式(或者也叫高斯算法)。

公式名 公式
等差数列求和公式(高斯算法) 1 + 2 + + n = n ( n + 1 ) 2 . 1 + 2 + \cdots + n = \frac {n(n+1)} {2}.

题解代码

HDU(C++/G++)AC代码如下:

#include <iostream>
#include <algorithm>

using namespace std;

int main()
{
	ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);

	long long n;
	while (cin >> n)
		cout << n * (n + 1) / 2 << '\n' << endl;

	return 0;
}

评价

这道题也算是一道入门题吧。

发布了3 篇原创文章 · 获赞 3 · 访问量 44

猜你喜欢

转载自blog.csdn.net/qq_44220418/article/details/104433709