Numbers with a Fibonacci difference between Sum of digits at even and odd positions in a given range
Prerequisites: Digit DP Given a range [L, R], the task is to count the numbers in this range having the difference between, the sum of digits at even positions and sum of digits at odd positions, as a Fibonacci Number. Note: Consider the position of the least significant digit in the number as an odd position. Examples:
Input: L = 1, R = 10 Output: 1 Explanation: The only number which satisfies the given condition is 10. Input: L = 50, R = 100 Output: 27
Approach: The idea is to use the concept of Dynamic Programming to solve this problem. The concept of digit dp is used to form a DP table.
- A four-dimensional table is formed and at every recursive call, we need to check whether the required difference is a Fibonacci number or not.
- Since the highest number in the range is 1018, the maximum sum at either even or odd positions can be at max 9 times 9 and hence the maximum difference. So, we need to check only Fibonacci numbers only up to 100 at the base condition.
- To check whether the number is Fibonacci or not, generate all the Fibonacci numbers and create a hash set.
The following are the DP states of the table:
- Since we can consider our number as a sequence of digits, one state is the position at which we are currently at. This position can have values from 0 to 18 if we are dealing with the numbers up to 1018. In each recursive call, we try to build the sequence from left to right by placing a digit from 0 to 9.
- First state is the sum of the digits at even positions we have placed so far.
- Second state is the sum of the digits at odd positions we have placed so far.
- Another state is the boolean variable tight which tells the number we are trying to build has already become smaller than R so that in the upcoming recursive calls we can place any digit from 0 to 9. If the number has not become smaller, the maximum limit of digit we can place at the current position in R.
Below is the implementation of the above approach:
My Personal Notes arrow_drop_up
Please Login to comment...