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.
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. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Note: Consider the position of the least significant digit in the number as an odd position.
Input: L = 1, R = 10
The only number which satisfies the given condition is 10.
Input: L = 50, R = 100
- 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: