Blue Bridge Cup induction training: 2 sequence summing

1, induction training sequence summing

Title Problem Description

+ ... find the value of 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.
Input Sample
4
Sample Output
10
Sample Input
100

Note: 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.

We must pay attention to the size of the data here.

Topic Analysis:

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 ready to use printf output, then your format string should be written% I64d to output a long long integer types.

Here is the code


public class sy02 {
	public static void main(String[] args) {
		Scanner Scan = new Scanner(System.in);
		System.out.println("请输入要计算的值:");
		int n = Scan.nextInt();
		int sum = 0;
		if (1 <= n && n <= 10000000) {
			for (int i = 1; i <= n; i++) {
				sum = i + sum;//递加得出结果
			}
			System.out.println(sum);
		}
	}
}

发布了2 篇原创文章 · 获赞 1 · 访问量 14

Guess you like

Origin blog.csdn.net/W958820499/article/details/104010648