[Blue] [entry] Bridge Cup series summation

Problem description
evaluation 1 + 2 + 3 + ... + n is.
Input format
input comprises an integer n.
Output format
output line, including an integer representing the value 1 + 2 + 3 + ... + n is.
Sample Input
4
Sample output
10
Sample input
100
Description: There are some sample questions will give multiple sets of input and output to help you do a better title.

General prior to the submission of all these samples are to be tested by the job, but that does not mean that these set of sample data are correct your program is entirely correct potential errors may still lead to lower your score.

Sample output
5050
data size and Conventions
1 <= n <= 1,000,000,000.
Note: Please note that the size of the data here.

The idea is to direct this question directly use a loop to accumulate, however, when the method is large-scale data, this "violence" often leads to a timeout. At this point you need to think of other methods. You can try, if you use 1 billion as the input your program, your program is not able to run out within the time stipulated in the above provisions.
Another problem for noteworthy that this place is the size of the answer is not in your default language of integer (int) in the range, if you use an integer to hold the result, the result will lead to error.
If you are using C or C ++ language and are ready to use printf output, then your format string should be written% I64d to output a long long integer types.

#include <stdio.h>
using namespace std;
int main()
{
	long long n;
	scanf("%I64d", &n);
	if (n % 2 == 0)
		n = (n + 1) * n / 2;
	else
		n = n * (n / 2 + 1);
	printf("%I64d", n);
}
Released six original articles · won praise 0 · Views 74

Guess you like

Origin blog.csdn.net/weixin_43842260/article/details/104076226