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))
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Greatest divisor which divides all natural number in range [L, R]
- Find elements in a given range having at least one odd divisor
- Generating numbers that are divisor of their right-rotations
- Number of ways to obtain each numbers in range [1, b+c] by adding any two numbers in range [a, b] and [b, c]
- Sum of all even numbers in range L and R
- Sum of all odd factors of numbers in the range [l, r]
- Prime numbers in a given range using STL | Set 2
- Count Odd and Even numbers in a range from L to R
- Sum of Fibonacci Numbers in a range
- Sum of all natural numbers in range L to R
- Sum of all odd natural numbers in range L and R
- Find XOR of numbers from the range [L, R]
- Sum of all numbers in the given range which are divisible by M
- Check whether XOR of all numbers in a given range is even or odd
- Sum of all numbers divisible by 6 in a given range
- Panarithmic numbers within a given range
- Sum of all the prime numbers in a given range
- Sum of all even factors of numbers in the range [l, r]
- Count of numbers having only 1 set bit in the range [0, n]
- Count of numbers with all digits same in a given range