java分治法求一维数组的和
时间: 2024-06-13 07:06:52 浏览: 82
java 数组求和计算
4星 · 用户满意度95%
以下是Java分治法求一维数组的和的代码实现:
```java
public class DivideSum {
public static int divideSum(int[] a, int l, int r) {
int sum = 0;
if (l == r) {
return a[l];
}
int m = (l + r) / 2;
int lsum = divideSum(a, l, m);
int rsum = divideSum(a, m + 1, r);
sum = lsum + rsum;
return sum;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
int l = sc.nextInt();
int r = sc.nextInt();
int result = divideSum(a, l, r);
System.out.println(result);
}
}
```
阅读全文