Sum of the elements from index L to R in an array when arr[i] = i * (-1)^i in C++

C++Server Side ProgrammingProgramming

In this problem, we are given two numbers L and R. We also have an array arr[] such that arr[i] = i*(-1)^i. Our task is to create a program to calculate the sum of the element from index L to R in an array when arr[i] = i*(-1)^i.

So, we need to find the sum of elements within the range [L, R] of the array.

Let’s take an example to understand the problem,

Input 

L = 2 , R = 6

Output 

4

Explanation 

arr[] = {-1, 2, -3, 4, -5, 6}
Sum = 2+ (-3) + 4 + (-5) + 6 = 4

A simple solution to the problem will be running a loop from L to R and then adding all even numbers and subtracting all odd numbers. And then finally return the sum.

Example

Program to illustrate the working of our solution,

 Live Demo

#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;
}

Output

Sum of elements of array from index 3 to 15 is -9

This is not an effective approach and will solve the problem in O(n) time complexity.

An efficient solution would be using the formula for the sum of n odd numbers. So,

Sum of first n odd numbers = n*n

Sum of first n even numbers = n*(n+1)

Here, the final sum will be calculated as

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 )

* There will be N/2 even/odd number till n. i.e. there will be R/2 even number. So, we will use R/2 and L/2 to calculate the sum.

Example

Program to illustrate the working of our solution,

 Live Demo

#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;
}

Output

Sum of elements of array from index 3 to 15 is -9
raja
Updated on 06-Aug-2020 08:12:58

Advertisements