The sequence first consists of all the odd numbers starting from 1 to n and then remaining even numbers starting 2 up to n. Let’s suppose we have n as 1000. Then the sequence becomes 1 3 5 7….999 2 4 6….1000
We are given a range (L, R), we need to find sum of numbers of this sequence in given range.
Note: Here the range is given as (L, R) L and R are included in the range
Input : n = 10 Range 1 6 Output : 27 Explanation: Sequence is 1 3 5 7 9 2 4 6 8 10 Sum in range (2, 6) = 1 + 3 + 5 + 7 + 9 + 2 = 27 Input : n = 5 Range 1 2 Output : 4 Explanation: sequence is 1 3 5 2 4 sum = 1 + 3 = 4
The idea is to first find sum of numbers before left(excluding left), then find sum of numbers before right (including right). We get result as second sum minus first sum.
How to find count of odd numbers?
- If n is odd then the number of odd numbers are ((n/2) + 1)
- If n is even then number of odd numbers are (n/2)
By simple observation, we get the number of odd numbers is ceil(n/2). So, the number of even numbers are n – ceil(n/2).
- Sum of first N odd numbers is (N^2)
- Sum of first N even numbers is (N^2) + N
For a given number x how will we find the sum in the sequence from 1 to x?
let’s suppose x is less than the number of odd numbers.
- Then we simply return (x*x)
If the x is greater then the number of odd numbers
- Sum of all natural numbers in range L to R
- Sum of all odd natural numbers in range L and R
- Greatest divisor which divides all natural number in range [L, R]
- LCM of First n Natural Numbers
- Sum of first n natural numbers
- Natural Numbers
- Repeated sum of first N natural numbers
- Average of first n even natural numbers
- Sum of fifth powers of the first n natural numbers
- Sum of first N natural numbers which are not powers of K
- Sum of first N natural numbers which are divisible by X or Y
- Sum of cubes of first n odd natural numbers
- Sum of squares of first n natural numbers
- Sum of cubes of even and odd natural numbers
- Sum of first N natural numbers which are divisible by 2 and 7
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.