Sum of all natural numbers in range L to R
Last Updated :
27 Aug, 2022
Given a range L and R, the task is to find the sum of all natural numbers in range L to R.
Examples:
Input: L = 2, R = 5
Output: 14
2 + 3 + 4 + 5 = 14
Input: L = 10, R = 20
Output: 165
A naive approach is to traverse from L to R and add all the elements one by one to get the sum.
An efficient approach is to use the formula for the sum of first N natural numbers. The idea of the inclusion-exclusion principle helps to solve the above problem. Find the sum of natural numbers till R and L-1 and then subtract sum(R)-sum(l-1).
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int sumNatural( int n)
{
int sum = (n * (n + 1)) / 2;
return sum;
}
int suminRange( int l, int r)
{
return sumNatural(r) - sumNatural(l - 1);
}
int main()
{
int l = 2, r = 5;
cout << "Sum of Natural numbers from L to R is "
<< suminRange(l, r);
return 0;
}
|
Java
class GFG{
static int sumNatural( int n)
{
int sum = (n * (n + 1 )) / 2 ;
return sum;
}
static int suminRange( int l, int r)
{
return sumNatural(r) - sumNatural(l - 1 );
}
public static void main(String[] args)
{
int l = 2 , r = 5 ;
System.out.println( "Sum of Natural numbers from L to R is " +suminRange(l, r));
}
}
|
Python3
def sumNatural(n):
sum = (n * (n + 1 )) / / 2
return sum
def suminRange(l, r):
return sumNatural(r) - sumNatural(l - 1 )
l = 2 ; r = 5
print ( "Sum of Natural numbers from L to R is " ,suminRange(l, r))
|
C#
using System;
class GFG
{
static int sumNatural( int n)
{
int sum = (n * (n + 1)) / 2;
return sum;
}
static int suminRange( int l, int r)
{
return sumNatural(r) -
sumNatural(l - 1);
}
static public void Main ()
{
int l = 2, r = 5;
Console.WriteLine( "Sum of Natural numbers " +
"from L to R is " +
suminRange(l, r));
}
}
|
PHP
<?php
function sumNatural( $n )
{
$sum = ( $n * ( $n + 1)) / 2;
return $sum ;
}
function suminRange( $l , $r )
{
return sumNatural( $r ) -
sumNatural( $l - 1);
}
$l = 2;
$r = 5;
echo "Sum of Natural numbers " .
"from L to R is " ,
suminRange( $l , $r );
?>
|
Javascript
<script>
function sumNatural(n)
{
sum = (n * (n + 1)) / 2;
return sum;
}
function suminRange(l, r)
{
return sumNatural(r) -
sumNatural(l - 1);
}
let l = 2;
let r = 5;
document.write( "Sum of Natural numbers from L to R is " +
suminRange(l, r));
</script>
|
Output:
Sum of Natural numbers from L to R is 14
Time Complexity: O(1)
Auxiliary Space: O(1), since no extra space has been taken.
Share your thoughts in the comments
Please Login to comment...