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:
Sum of odd natural numbers from L to R is 8
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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.
Be the First to upvote.
Please write to us at email@example.com to report any issue with the above content.
thanks you RSS link