Given an interval of integers [A, B]. For each number in this interval compute its greatest odd divisor. Output the sum of these divisors.
Input : A = 1, B = 3 Output : 5 1 + 1 + 3 = 5 Input : A = 3, B = 9 Output : 29 3 + 1 + 5 + 3 + 7 + 1 + 9 = 29
Naive Approach :
A simple approach is to iterate through all numbers in the range find their greatest odd divisor but this algorithm has time complexity of O(n).
Efficient Approach :
We need to find the answer in range [ A, B ] if we can find answer in range [ 1, B ] and subtract it from [ 1, A -1 ] then we will get our required answer.
Here we can see that –
- The answer for an odd number X is X itself.
- The answer for an even number X is equal to the answer for X/2. This is true because X and X/2 have the same odd divisors.( if X = 4 then 4 and 2 both have 1 as greatest odd divisor).
If we want to find answer in range [1, N], then first we need to determine the sum of all the odd numbers
( 1, 3, 5, …) using a simple formula: the sum of the first K odd numbers is equal to K2. Then we need to add the answers for the even numbers (2, 4, 6, …). But these are actually equal to the answers for 1, 2, 3, …, floor(N/2), so we can call our function recursively for floor(N/2).
The complexity of this algorithm is O(log( N)).
Below is the implementation of the above idea :
Time Complexity : O(log(N))
- Greatest divisor which divides all natural number in range [L, R]
- Generating numbers that are divisor of their right-rotations
- Sum of all even numbers in range L and R
- Sum of all the prime numbers in a given range
- Sum of all odd natural numbers in range L and R
- Sum of all natural numbers in range L to R
- Sum of all even factors of numbers in the range [l, r]
- Check whether XOR of all numbers in a given range is even or odd
- Count of numbers having only 1 set bit in the range [0, n]
- Count Odd and Even numbers in a range from L to R
- Sum of all numbers divisible by 6 in a given range
- Prime numbers in a given range using STL | Set 2
- Sum of Fibonacci Numbers in a range
- Find XOR of numbers from the range [L, R]
- Sum of all odd factors of numbers in the range [l, r]
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.