Calculate the sum of sum of numbers in range L to R
Given two numbers L and R. The task is to find the sum of numbers in the range L to R.
Examples:
Input: L = 3, R = 6
Output: 40
Explanation: 3 + 3+4 + 3+4+5 + 3+4+5+6 = 40
Input: L = 5, R = 6
Output: 16
Approach: This problem is formula-based. For the illustration given below, observe the number of times each number is repeating in the sum, and depending upon that the final sum is calculated.
Illustration: L = 3, R = 6
Sum = 3 + 3+4 + 3+4+5 + 3+4+5+6 = 3+3+3+3 + 4+4+4 + 5+5 + 6 (Upon Grouping)
That is equals to 3*4 + 4*3 + 5*2 + 6*1
Therefore for any range L to R, the sum can be calculated as:
L*D + (L+1)*(D-1) + (L+2)*(D-2) + … + (R-1)*(2) + R*1
Below is the implementation of above approach.
C++
#include <iostream>
using namespace std;
int findSum( int L, int R)
{
int sum = 0, d = R - L + 1;
for ( int i = L; i <= R; i++) {
sum += (i * d);
d--;
}
return sum;
}
int main()
{
int L = 3, R = 6;
cout << findSum(L, R);
return 0;
}
|
Java
import java.util.*;
public class GFG {
static int findSum( int L, int R)
{
int sum = 0 , d = R - L + 1 ;
for ( int i = L; i <= R; i++) {
sum += (i * d);
d--;
}
return sum;
}
public static void main(String args[])
{
int L = 3 , R = 6 ;
System.out.println(findSum(L, R));
}
}
|
Python
def findSum(L, R):
sum = 0
d = R - L + 1
for i in range (L, R + 1 ):
sum + = (i * d)
d = d - 1
return sum
L = 3
R = 6
print (findSum(L, R))
|
C#
using System;
public class GFG {
static int findSum( int L, int R)
{
int sum = 0, d = R - L + 1;
for ( int i = L; i <= R; i++) {
sum += (i * d);
d--;
}
return sum;
}
public static void Main()
{
int L = 3, R = 6;
Console.WriteLine(findSum(L, R));
}
}
|
Javascript
<script>
function findSum(L, R) {
let sum = 0, d = R - L + 1;
for (let i = L; i <= R; i++) {
sum += (i * d);
d--;
}
return sum;
}
let L = 3, R = 6;
document.write(findSum(L, R));
</script>
|
Time Complexity: O(R-L+1)
Auxiliary Space: O(1), since no extra space has been taken.
Last Updated :
27 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...