题目
Write a program that finds the summation of every number from 1 to num. The number will always be a positive integer greater than 0.
For example:
summation(2) -> 3
1 + 2
summation(8) -> 36
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8
解析
编写一个程序,查找从1到num的每个数字的总和。该数字始终是大于0的正整数。
我的答案
public static int summation(int n) {
return IntStream.rangeClosed(1,n).sum();
}
最优答案
public static int summation(int n) {
return n*(n+1)/2;
}