Sum of all even numbers in range L and R
Last Updated :
11 Jul, 2022
Given two integers L and R, the task is to find the sum of all even numbers in range L and R.
Examples:
Input: L = 2, R = 5
Output: 6
2 + 4 = 6
Input: L = 3, R = 8
Output: 18
Method-1: Iterate from L to R and sum all the even numbers in that range.
Method-2: Find the sum all the natural numbers from L to R and subtract the sum of odd natural numbers in range L to R from it.
Method-3:
- Find the sum of all even numbers up to R i.e. No. of even numbers up to R will be R/2.
- Find the sum of all even numbers up to L-1 i.e. No. of even numbers up to L-1 will be (L-1)/2.
- Then subtract sumUptoL from sumuptoR.
Sum of all even numbers up to any N will be:
R*(R+1) where R = N/2
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));
return sum;
}
int sumEven( int l, int r)
{
return sumNatural(r/2) - sumNatural((l-1) / 2);
}
int main()
{
int l = 2, r = 5;
cout << "Sum of Natural numbers from L to R is "
<< sumEven(l, r);
return 0;
}
|
Java
import java.io.*;
class GFG {
static int sumNatural( int n)
{
int sum = (n * (n + 1 ));
return sum;
}
static int sumEven( int l, int r)
{
return sumNatural(r/ 2 ) - sumNatural((l- 1 ) / 2 );
}
public static void main (String[] args) {
int l = 2 , r = 5 ;
System.out.println ( "Sum of Natural numbers from L to R is " +
sumEven(l, r));
}
}
|
Python3
def sumNatural(n):
sum = (n * (n + 1 ))
return int ( sum )
def sumEven(l, r):
return (sumNatural( int (r / 2 )) -
sumNatural( int ((l - 1 ) / 2 )))
l, r = 2 , 5
print ( "Sum of Natural numbers" ,
"from L to R is" , sumEven(l, r))
|
C#
using System;
public class GFG{
static int sumNatural( int n)
{
int sum = (n * (n + 1));
return sum;
}
static int sumEven( int l, int r)
{
return sumNatural(r/2) - sumNatural((l-1) / 2);
}
static public void Main (){
int l = 2, r = 5;
Console.WriteLine( "Sum of Natural numbers from L to R is " +
sumEven(l, r));
}
}
|
PHP
<?php
function sumNatural( $n )
{
$sum = ( $n * ( $n + 1));
return $sum ;
}
function sumEven( $l , $r )
{
return sumNatural((int)( $r / 2)) -
sumNatural((int)(( $l - 1) / 2));
}
$l = 2; $r = 5;
echo "Sum of Natural numbers " .
"from L to R is " . sumEven( $l , $r );
?>
|
Javascript
<script>
function sumNatural(n)
{
let sum = Math.floor(n * (n + 1));
return sum;
}
function sumEven(l, r)
{
return sumNatural(Math.floor(r/2)) - sumNatural(Math.floor(l-1) / 2);
}
let l = 2, r = 5;
document.write ( "Sum of Natural numbers from L to R is " +
sumEven(l, r));
</script>
|
Output:
Sum of Natural numbers from L to R is 6
Time Complexity: O(1), since there is no loop or recursion.
Auxiliary Space: O(1), since no extra space has been taken.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...