Sum of all odd natural numbers in range L and R

• Last Updated : 05 Apr, 2021

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++

 // C++ program to print the sum// of all numbers in range L and R#include using namespace std; // Function to return the sum of// all odd natural numbersint sumOdd(int n){    int terms = (n + 1) / 2;    int sum = terms * terms;    return sum;} // Function to return the sum// of all odd numbers in range L and Rint suminRange(int l, int r){    return sumOdd(r) - sumOdd(l - 1);} // Driver Codeint main(){    int l = 2, r = 5;    cout << "Sum of odd natural numbers from L to R is "         << suminRange(l, r);     return 0;}

Java

 // Java program to print the sum// of all numbers in range L and R import java.io.*; class GFG {      // Function to return the sum of// all odd natural numbersstatic int sumOdd(int n){    int terms = (n + 1) / 2;    int sum = terms * terms;    return sum;} // Function to return the sum// of all odd numbers in range L and Rstatic int suminRange(int l, int r){    return sumOdd(r) - sumOdd(l - 1);} // Driver Codepublic 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));    }}// This code is contributed by shs..

Python3

 # Python 3 program to print the sum# of all numbers in range L and R # Function to return the sum of# all odd natural numbersdef sumOdd(n):    terms = (n + 1)//2    sum1 = terms * terms    return sum1 # Function to return the sum# of all odd numbers in range L and Rdef suminRange(l, r):    return sumOdd(r) - sumOdd(l - 1)     # Driver codel = 2; r = 5print("Sum of odd natural number",      "from L to R is", suminRange(l, r)) # This code is contributed by Shrikant13

C#

 // C# program to print the sum// of all numbers in range L and Rusing System; class GFG{     // Function to return the sum of// all odd natural numbersstatic int sumOdd(int n){    int terms = (n + 1) / 2;    int sum = terms * terms;    return sum;} // Function to return the sum// of all odd numbers in range L and Rstatic int suminRange(int l, int r){    return sumOdd(r) - sumOdd(l - 1);} // Driver Codepublic static void Main (){    int l = 2, r = 5;    Console.WriteLine( "Sum of odd natural numbers " +                "from L to R is " + suminRange(l, r));}} // This code is contributed by shs..



Javascript


Output:
Sum of odd natural numbers from L to R is 8

My Personal Notes arrow_drop_up