Find n-th element in a series with only 2 digits (4 and 7) allowed
Consider a series of numbers composed of only digits 4 and 7. First few numbers in the series are 4, 7, 44, 47, 74, 44744,.. etc. Given a number n, we need to find n-th number in the series.
Input : n = 2 Output : 7 Input : n = 3 Output : 44 Input : n = 5 Output : 74 Input : n = 6 Output : 77
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
The idea is based on the fact that the value of last digit alternates in series. For example, if last digit of i-th number is 4, then last digit of (i-1)-th and (i+1)-th numbers must be 7.
We create an array of size (n+1) and push 4 and 7 (These two are always first two elements of series) to it. For more elements we check
1) If i is odd,
arr[i] = arr[i/2]*10 + 4;
2) If it is even,
arr[i] = arr[(i/2)-1]*10 + 7;
At last return arr[n].
Find n-th element in a series with only 2 digits (4 and 7) allowed | Set 2 (log(n) method)
This article is contributed by Roshni Agarwal. 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 write comments if you find anything incorrect, or you want to share more information about the topic discussed above.