给定一个正整数n(1<=n<=100),采用迭代算法和递归算法求s = 1+(1+2)+(1+2+3)+...+(1+2+....n) Java
时间: 2024-06-15 14:08:16 浏览: 194
用递归求1+2+3+...+n的程序
可以使用迭代算法和递归算法来求解给定正整数n的表达式s = 1+(1+2)+(1+2+3)+...+(1+2+....n)。
迭代算法实现如下:
```java
public class IterativeAlgorithm {
public static int calculateSum(int n) {
int sum = 0;
int tempSum = 0;
for (int i = 1; i <= n; i++) {
tempSum += i;
sum += tempSum;
}
return sum;
}
public static void main(String[] args) {
int n = 5;
int result = calculateSum(n);
System.out.println("The sum is: " + result);
}
}
```
递归算法实现如下:
```java
public class RecursiveAlgorithm {
public static int calculateSum(int n) {
if (n == 1) {
return 1;
} else {
return calculateSum(n - 1) + (n * (n + 1)) / 2;
}
}
public static void main(String[] args) {
int n = 5;
int result = calculateSum(n);
System.out.println("The sum is: " + result);
}
}
```
阅读全文