Problem Statement: Find the sum of numbers in the given range.
Examples:
Example 1: Input: l=2, r=7 Output: 27 Explanation: 2+3+4+5+6+7=27. Therefore 27 is the answer. Example 2: Input: l=5, r=9 Output: 35 Explanation: 5+6+7+8+9=35. Therefore 35 is the answer.
Solution 1:Naive approach
Intuition: Simply add numbers from l to r.
Approach:
- Maintain a sum variable to store the sum of elements from l to r.
- Traverse from l to r and add i to the sum.
- Once the traversal is complete print the sum.
Code:
C++ Code
#include<bits/stdc++.h>
using namespace std;
int main()
{
int l = 2, r = 7;
int sum = 0;
for (int i = l; i <= r; i++) {
sum += i;
}
cout << "The sum of numbers in the given range is "<<sum;
}
Output: The sum of the numbers in the given range is 27
Java Code
public class Main {
public static void main(String args[]) {
int l = 2, r = 7;
int sum = 0;
for (int i = l; i <= r; i++) {
sum += i;
}
System.out.print("The sum of the numbers in the given range is "+sum);
}
}
Output: The sum of the numbers in the given range is 27
Solution 2: Optimized
Intuition: Find the sum of numbers from 1 to r and then subtract the sum of numbers from 1 to l-1 to get the sum of elements from l to r.
Approach:
- We know sum of number from 1 to n is n*(n+1)/2.
- We need to find sum(r)-sum(l-1),where sum(r) is the sum of numbers from 1 to r and sum(l-1) is the sum of numbers from 1 to l-1.
- So ultimately r*(r+1)/2 – (l-1)(l-1+1)/2 is the answer.
Code:
C++ Code
#include<bits/stdc++.h>
using namespace std;
int main()
{
int l = 2, r = 7;
//sum(1 to r) - sum(1 to l-1)
int ans = (r * (r + 1)) / 2 - ((l - 1) * (l)) / 2;
cout << "The sum of the numbers in the given range is "<<ans;
}
Output: The sum of the numbers in the given range is 27
Time Complexity: O(1), since we are finding sum from 1 to r and sum from 1 to l-1 in O(1) complexity.
Space Complexity: O(1).
Java Code
public class Main {
public static void main(String args[]) {
int l = 2, r = 7;
//sum(1 to r) - sum(1 to l-1)
int ans = (r * (r + 1)) / 2 - ((l - 1) * (l)) / 2;
System.out.print("The sum of the numbers in the given range is "+ans);
}
}
Output: The sum of the numbers in the given range is 27
Time Complexity: O(1), since we are finding sum from 1 to r and sum from 1 to l-1 in O(1) complexity.
Space Complexity: O(1).
Special thanks to Pranav Padawe for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam, please check out this article