Given two integers L and R, the task is to find the sum of all in L and R inclusive.


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:

#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;


Sum of odd natural numbers from L to R is 8

Just another competitive programmer

If you like and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the “Improve Article” button below.

Article Tags :

Be the First to upvote.

Please write to us at to report any issue with the above content.

Source link
thanks you RSS link


Please enter your comment!
Please enter your name here