Sum of all odd natural numbers in range L and R
Last Updated :
28 Aug, 2022
Given two integers L and R, the task is to find the sum of all odd natural numbers in range L and R inclusive.
Examples:
Input: L = 2, R = 5
Output: 8
3 + 5 = 8
Input: L = 7, R = 13
Output: 40
A naive approach is to traverse from L to R and summate the elements to get the answer.
An efficient approach is to use the formula for calculating the sum of all odd natural numbers upto 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 sumOdd( int n)
{
int terms = (n + 1) / 2;
int sum = terms * terms;
return sum;
}
int suminRange( int l, int r)
{
return sumOdd(r) - sumOdd(l - 1);
}
int main()
{
int l = 2, r = 5;
cout << "Sum of odd natural numbers from L to R is "
<< suminRange(l, r);
return 0;
}
|
Java
import java.io.*;
class GFG {
static int sumOdd( int n)
{
int terms = (n + 1 ) / 2 ;
int sum = terms * terms;
return sum;
}
static int suminRange( int l, int r)
{
return sumOdd(r) - sumOdd(l - 1 );
}
public static void main (String[] args) {
int l = 2 , r = 5 ;
System.out.print( "Sum of odd natural numbers from L to R is "
+ suminRange(l, r));
}
}
|
Python3
def sumOdd(n):
terms = (n + 1 ) / / 2
sum1 = terms * terms
return sum1
def suminRange(l, r):
return sumOdd(r) - sumOdd(l - 1 )
l = 2 ; r = 5
print ( "Sum of odd natural number" ,
"from L to R is" , suminRange(l, r))
|
C#
using System;
class GFG
{
static int sumOdd( int n)
{
int terms = (n + 1) / 2;
int sum = terms * terms;
return sum;
}
static int suminRange( int l, int r)
{
return sumOdd(r) - sumOdd(l - 1);
}
public static void Main ()
{
int l = 2, r = 5;
Console.WriteLine( "Sum of odd natural numbers " +
"from L to R is " + suminRange(l, r));
}
}
|
PHP
<?php
function sumOdd( $n )
{
$terms = (int)( $n + 1) / 2;
$sum = $terms * $terms ;
return $sum ;
}
function suminRange( $l , $r )
{
return sumOdd( $r ) - sumOdd( $l - 1);
}
$l = 2;
$r = 5;
echo "Sum of odd natural numbers from L to R is " ,
suminRange( $l , $r );
?>
|
Javascript
<script>
function sumOdd(n)
{
terms = (n + 1) / 2;
sum = terms * terms;
return sum;
}
function suminRange(l, r)
{
return sumOdd(r) - sumOdd(l - 1);
}
let l = 2;
let r = 5;
document.write( "Sum of odd natural numbers from L to R is " +
suminRange(l, r));
</script>
|
Output:
Sum of odd natural numbers from L to R is 8
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...