Sum of elements of an AP in the given range
Last Updated :
20 Sep, 2023
Given an arithmetic series in arr and Q queries in the form of [L, R], where L is the left boundary of the range and R is the right boundary. The task is to find the sum of the AP elements in the given range.
Note: The range is 1-indexed and 1 ? L, R ? N, where N is the size of arr.
Examples:
Input: arr[] = {2, 4, 6, 8, 10, 12, 14, 16}, Q = [[2, 4], [2, 6], [5, 8]]
Output:
18
40
52
Explanation:
Range 1: arr = {4, 6, 8}. Therefore sum = 18
Range 2: arr = {4, 6, 8, 10, 12}. Therefore sum = 40
Range 3: arr = {10, 12, 14, 16}. Therefore sum = 52
Input: arr[] = {7, 14, 21, 28, 35, 42}, Q = [[1, 6], [2, 4], [3, 3]]
Output:
147
63
21
Explanation:
Range 1: arr = {7, 14, 21, 28, 35, 42}. Therefore sum = 147
Range 2: arr = {14, 21, 28}. Therefore sum = 63
Range 3: arr = {21}. Therefore sum = 21
Approach: Since the given sequence is an arithmetic progression, the sum can be easily found in two steps efficiently:
- Multiply the first element of the range by the number of elements in the range.
- Add (d*k*(k+1))/2 to it, where d is the common difference of the AP and k is (number of elements in the range - 1) which corresponds to the number of gaps.
For example:
Suppose a[i] be the first element of the range, d is the common difference of AP and k+1 be the number of elements in the given range.
Then the sum of the range would be
= a[i] + a[i+1] + a[i+2] + ..... + a[i+k]
= a[i] + a[i] + d + a[i] + 2 * d + .... + a[i] + k * d
= a[i] * (k + 1) + d * (1 + 2 + ... + k)
= a[i] * (k + 1) + (d * k * (k+1))/2
Below is the implementation of the above approach:
CPP
// C++ program to find the sum of elements
// of an AP in the given range
#include <bits/stdc++.h>
using namespace std;
// Function to find sum in the given range
int findSum(int* arr, int n,
int left, int right)
{
// Find the value of k
int k = right - left;
// Find the common difference
int d = arr[1] - arr[0];
// Find the sum
int ans = arr[left - 1] * (k + 1);
ans = ans + (d * (k * (k + 1))) / 2;
return ans;
}
// Driver code
int main()
{
int arr[] = { 2, 4, 6, 8, 10, 12, 14, 16 };
int queries = 3;
int q[queries][2] = { { 2, 4 },
{ 2, 6 },
{ 5, 6 } };
int n = sizeof(arr) / sizeof(arr[0]);
for (int i = 0; i < queries; i++)
cout << findSum(arr, n, q[i][0], q[i][1])
<< endl;
}
Java
// Java program to find the sum of elements
// of an AP in the given range
class GFG{
// Function to find sum in the given range
static int findSum(int []arr, int n,
int left, int right)
{
// Find the value of k
int k = right - left;
// Find the common difference
int d = arr[1] - arr[0];
// Find the sum
int ans = arr[left - 1] * (k + 1);
ans = ans + (d * (k * (k + 1))) / 2;
return ans;
}
// Driver code
public static void main(String[] args)
{
int arr[] = { 2, 4, 6, 8, 10, 12, 14, 16 };
int queries = 3;
int q[][] = { { 2, 4 },
{ 2, 6 },
{ 5, 6 } };
int n = arr.length;
for (int i = 0; i < queries; i++)
System.out.print(findSum(arr, n, q[i][0], q[i][1])
+"\n");
}
}
// This code is contributed by Princi Singh
Python3
# Python program to find the sum of elements
# of an AP in the given range
# Function to find sum in the given range
def findSum(arr, n, left, right):
# Find the value of k
k = right - left;
# Find the common difference
d = arr[1] - arr[0];
# Find the sum
ans = arr[left - 1] * (k + 1);
ans = ans + (d * (k * (k + 1))) // 2;
return ans;
# Driver code
if __name__ == '__main__':
arr = [ 2, 4, 6, 8, 10, 12, 14, 16 ];
queries = 3;
q = [[ 2, 4 ],[ 2, 6 ],[ 5, 6 ]];
n = len(arr);
for i in range(queries):
print(findSum(arr, n, q[i][0], q[i][1]));
# This code is contributed by sapnasingh4991
C#
// C# program to find the sum of elements
// of an AP in the given range
using System;
class GFG{
// Function to find sum in the given range
static int findSum(int []arr, int n,
int left, int right)
{
// Find the value of k
int k = right - left;
// Find the common difference
int d = arr[1] - arr[0];
// Find the sum
int ans = arr[left - 1] * (k + 1);
ans = ans + (d * (k * (k + 1))) / 2;
return ans;
}
// Driver code
public static void Main(String[] args)
{
int []arr = { 2, 4, 6, 8, 10, 12, 14, 16 };
int queries = 3;
int [,]q = { { 2, 4 },
{ 2, 6 },
{ 5, 6 } };
int n = arr.Length;
for (int i = 0; i < queries; i++)
Console.Write(findSum(arr, n, q[i,0], q[i,1])
+"\n");
}
}
// This code is contributed by PrinciRaj1992
JavaScript
<script>
// JavaScript program to find the sum of elements
// of an AP in the given range
// Function to find sum in the given range
function findSum(arr, n, left, right)
{
// Find the value of k
let k = right - left;
// Find the common difference
let d = arr[1] - arr[0];
// Find the sum
let ans = arr[left - 1] * (k + 1);
ans = ans + (d * (k * (k + 1))) / 2;
return ans;
}
// Driver Code
let arr = [ 2, 4, 6, 8, 10, 12, 14, 16 ];
let queries = 3;
let q = [[ 2, 4 ],
[ 2, 6 ],
[ 5, 6 ]];
let n = arr.length;
for (let i = 0; i < queries; i++)
document.write(findSum(arr, n, q[i][0], q[i][1])
+"<br/>");
</script>
Time complexity: O(q), where q is the length of the given queries array.
Auxiliary Space: O(1)
Method 2: Using Prefix Sum
Approach:
- Create a prefix sum array for the given arithmetic series.
- For each query, calculate the sum of the range by subtracting the prefix sum at L-1 from the prefix sum at R.
- Output the sum for each query.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
vector<int> arithmetic_series_sum(int arr[], int N, vector<vector<int>> queries) {
// precompute prefix sum
int prefixSum[N];
prefixSum[0] = arr[0];
for (int i = 1; i < N; i++) {
prefixSum[i] = prefixSum[i - 1] + arr[i];
}
// process queries
vector<int> ans;
for (int i = 0; i < queries.size(); i++) {
int L = queries[i][0];
int R = queries[i][1];
int sum = prefixSum[R - 1] - prefixSum[L - 2];
ans.push_back(sum);
}
return ans;
}
int main() {
int arr[] = {2, 4, 6, 8, 10, 12, 14, 16};
int N = sizeof(arr) / sizeof(arr[0]);
// define queries
vector<vector<int>> queries = {{2, 4},{2, 6},{5, 6}};
// call function to compute arithmetic series sum for queries
vector<int> ans = arithmetic_series_sum(arr, N, queries);
// print answers
for (int i = 0; i < ans.size(); i++) {
cout << ans[i] << endl;
}
return 0;
}
Java
import java.util.ArrayList;
public class GFG {
public static ArrayList<Integer> arithmeticSeriesSum(
int[] arr, int N,
ArrayList<ArrayList<Integer> > queries)
{
// Precompute prefix sum
int[] prefixSum = new int[N];
prefixSum[0] = arr[0];
for (int i = 1; i < N; i++) {
prefixSum[i] = prefixSum[i - 1] + arr[i];
}
// Process queries
ArrayList<Integer> ans = new ArrayList<>();
for (int i = 0; i < queries.size(); i++) {
int L = queries.get(i).get(0);
int R = queries.get(i).get(1);
int sum = prefixSum[R - 1]
- (L > 1 ? prefixSum[L - 2] : 0);
ans.add(sum);
}
return ans;
}
public static void main(String[] args)
{
int[] arr = { 2, 4, 6, 8, 10, 12, 14, 16 };
int N = arr.length;
// Define queries
ArrayList<ArrayList<Integer> > queries
= new ArrayList<>();
queries.add(
new ArrayList<>(java.util.Arrays.asList(2, 4)));
queries.add(
new ArrayList<>(java.util.Arrays.asList(2, 6)));
queries.add(
new ArrayList<>(java.util.Arrays.asList(5, 6)));
// Call function to compute arithmetic series sum
// for queries
ArrayList<Integer> ans
= arithmeticSeriesSum(arr, N, queries);
// Print answers
for (int i = 0; i < ans.size(); i++) {
System.out.println(ans.get(i));
}
}
}
Python3
def arithmetic_series_sum(arr, N, queries):
# precompute prefix sum
prefixSum = [0] * N
prefixSum[0] = arr[0]
for i in range(1, N):
prefixSum[i] = prefixSum[i - 1] + arr[i]
# process queries
ans = []
for i in range(len(queries)):
L = queries[i][0]
R = queries[i][1]
# Compute the sum using prefix sums
sum = prefixSum[R - 1] - prefixSum[L - 2]
ans.append(sum)
return ans
if __name__ == "__main__":
arr = [2, 4, 6, 8, 10, 12, 14, 16]
N = len(arr)
# define queries
queries = [[2, 4], [2, 6], [5, 6]]
# call function to compute arithmetic series sum for queries
ans = arithmetic_series_sum(arr, N, queries)
# print answers
for i in range(len(ans)):
print(ans[i])
C#
using System;
using System.Collections.Generic;
class GFG
{
static List<int> ArithmeticSeriesSum(int[] arr, int N, List<List<int>> queries)
{
// precompute prefix sum
int[] prefixSum = new int[N];
prefixSum[0] = arr[0];
for (int i = 1; i < N; i++)
{
prefixSum[i] = prefixSum[i - 1] + arr[i];
}
// process queries
List<int> ans = new List<int>();
for (int i = 0; i < queries.Count; i++)
{
int L = queries[i][0];
int R = queries[i][1];
int sum = prefixSum[R - 1] - (L - 2 >= 0 ? prefixSum[L - 2] : 0);
ans.Add(sum);
}
return ans;
}
static void Main()
{
int[] arr = { 2, 4, 6, 8, 10, 12, 14, 16 };
int N = arr.Length;
// define queries
List<List<int>> queries = new List<List<int>> {
new List<int> { 2, 4 },
new List<int> { 2, 6 },
new List<int> { 5, 6 }
};
// call function to compute arithmetic series sum for queries
List<int> ans = ArithmeticSeriesSum(arr, N, queries);
// print answers
foreach (int value in ans)
{
Console.WriteLine(value);
}
}
}
JavaScript
function arithmeticSeriesSum(arr, N, queries) {
// precompute prefix sum
let prefixSum = [];
prefixSum[0] = arr[0];
for (let i = 1; i < N; i++) {
prefixSum[i] = prefixSum[i - 1] + arr[i];
}
// process queries
let ans = [];
for (let i = 0; i < queries.length; i++) {
let L = queries[i][0];
let R = queries[i][1];
let sum = prefixSum[R - 1] - (L > 1 ? prefixSum[L - 2] : 0);
ans.push(sum);
}
return ans;
}
let arr = [2, 4, 6, 8, 10, 12, 14, 16];
let N = arr.length;
// define queries
let queries = [[2, 4], [2, 6], [5, 6]];
// call function to compute arithmetic series sum for queries
let ans = arithmeticSeriesSum(arr, N, queries);
// print answers
for (let i = 0; i < ans.length; i++) {
console.log(ans[i]);
}
Time complexity: O(N + Q),N is the size of the arithmetic series and Q is the number of queries.
Auxiliary Space: O(N) for the prefix sum array.
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Array Data Structure Guide In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
4 min read
Sorting Algorithms A Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read