Blue Bridge cup of java induction training sequence summing

Started training sequence summing

Resource constraints

Time limit: 1.0s Memory Limit: 256.0MB

Problem Description

+ ... find the value of 1 + 2 + 3 + n is.

Input Format

It includes an input 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 convention

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.

import java.math.BigDecimal;
import java.util.*;

public class Main {
public static void main(String args[]) throws Exception {
Scanner in = new Scanner(System.in);
int n=in.nextInt();
long sum=0;
for(int i=1;i<=n;i++){
sum+=i;
}
System.out.println(sum);
}
}
Published 24 original articles · won praise 2 · Views 200

Guess you like

Origin blog.csdn.net/weixin_44570019/article/details/104515116