// 求1+2+3+...+99+100的和
public class Test_001 {
public static void main(String[] args) {
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum += i;
}
System.out.println(sum);
// 高斯算法
int totle = 0;
// 1+2+3+...+98+99+100
// 100+99+98+...+3+2+1
// (1+100)*100 / 2
totle = ((1 + 100) * 100) / 2;
System.out.println(totle);
}
}
输出结果:
5050
5050
本文通过两种方法计算1到100的所有整数之和:一种是使用循环结构逐个累加,另一种是利用数学家高斯发现的等差数列求和公式直接计算结果。
5576

被折叠的 条评论
为什么被折叠?



