Given two integers L and R, the task is to find the sum of all odd natural numbers in range 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:
Sum of odd natural numbers from L to R is 8
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Sum of range in a series of first odd then even natural numbers
- Sum of all natural numbers in range L to R
- Count numbers from given range having odd digits at odd places and even digits at even places
- Sum of cubes of even and odd natural numbers
- Sum of cubes of first n odd natural numbers
- Sum of fourth powers of first n odd natural numbers
- Sum of all odd length palindromic numbers within the range [L, R]
- Sum of all odd factors of numbers in the range [l, r]
- Sum of sum of all subsets of a set formed by first N natural numbers
- Count set bits in the Kth number after segregating even and odd from N natural numbers
- Count numbers in given range such that sum of even digits is greater than sum of odd digits
- Sum of elements in range L-R where first half and second half is filled with odd and even numbers
- Count of integers in a range which have even number of odd digits and odd number of even digits
- Sum of all natural numbers from L to R ( for large values of L and R )
- Count Numbers in Range with difference between Sum of digits at even and odd positions as Prime
- Number of ways to obtain each numbers in range [1, b+c] by adding any two numbers in range [a, b] and [b, c]
- Difference between sum of the squares of first n natural numbers and square of sum
- Difference between Sum of Cubes and Sum of First N Natural Numbers
- Sum of series formed by difference between product and sum of N natural numbers
- Check whether XOR of all numbers in a given range is even or odd
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.