C++中,数组arr[i] = i * (-1)^i时,计算索引L到R之间元素的和
在这个问题中,我们给出两个数字L和R。我们还有一个数组arr[],其中**arr[i] = i*(-1)^i**。我们的任务是创建一个程序来计算当arr[i] = i*(-1)^i时,数组中从索引L到R的元素之和。
因此,我们需要找到数组[L, R]范围内元素的总和。
让我们举个例子来理解这个问题:
输入
L = 2 , R = 6
输出
4
解释
arr[] = {-1, 2, -3, 4, -5, 6}
Sum = 2+ (-3) + 4 + (-5) + 6 = 4解决这个问题的一个简单方法是从L循环到R,然后将所有偶数相加,将所有奇数相减。最后返回总和。
示例
程序说明了解决方案的工作原理:
#include <iostream>
#include <math.h>
using namespace std;
int CalcArrSumLtoR(int L, int R) {
int sum = 0;
for (int i = L; i <= R; i++){
sum += (i * pow((-1), i));
}
return sum;
}
int main() {
int L = 3, R = 15;
cout<<"Sum of elements of array from index "<<L<<" to "<<R<<" is "lt;lt;CalcArrSumLtoR(L, R);
return 0;
}输出
Sum of elements of array from index 3 to 15 is -9
这不是一种有效的方法,它将以O(n)的时间复杂度解决问题。
一种有效的解决方案是使用求n个奇数和的公式。所以:
前n个奇数的和 = n*n
前n个偶数的和 = n*(n+1)
最终总和将计算为:
sum = (sum of first R even number - sum of first (L-1) even number ) - (sum of first R odd number - sum of first (L-1) odd number )
* 到n为止,将有N/2个偶数/奇数。即有R/2个偶数。因此,我们将使用R/2和L/2来计算总和。
示例
程序说明了解决方案的工作原理:
#include <iostream>
using namespace std;
long int findSum(int n, bool isEven) {
long int total = 0;
if(isEven == true){
total = (n) / 2;
return (total * (total+1));
}
else {
total = (n + 1) / 2;
return total * total;
}
}
int CalcArrSumLtoR(int L, int R) {
return (findSum(R, true) - findSum(L - 1, true))- (findSum(R, false) - findSum(L - 1, false));
}
int main() {
int L = 3, R = 15;
cout<<"Sum of elements of array from index "<<L<<" to "<<R<<" is "<<CalcArrSumLtoR(L, R);
return 0;
}输出
Sum of elements of array from index 3 to 15 is -9
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP