Consider a series of numbers composed of only digits 4 and 7. First few numbers in the series are 4, 7, 44, 47, 74, 77, 444, .. 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
We have discussed a O(n) solution in below post.
Find n-th element in a series with only 2 digits (4 and 7) allowed
In this post, a O(log n) solution is discussed which is based on below pattern in numbers. The numbers can be seen
"" / \ 4 7 / \ / \ 44 47 74 77 / \ / \ / \ / \
The idea is to fill the required number from end. We know can observe that the last digit is 4 if n is odd and last digit is 7 if n is even. After filling last digit, we move to parent node in tree. If n is odd, then parent node corresponds to (n-1/2. Else parent node corresponds to (n-2)/2.
In this code the total complexity is O(log n). Because while loop run log (n) times.
This article is contributed by Devanshu 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.
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.
- Find n-th element in a series with only 2 digits (4 and 7) allowed
- Find position of given term in a series formed with only digits 4 and 7 allowed
- Queries to find distance between two nodes of a Binary tree - O(logn) method
- Find the Nth element of the modified Fibonacci series
- Find n-th element from Stern's Diatomic Series
- Find the average of k digits from the beginning and l digits from the end of the given number
- Factorial of each element in Fibonacci series
- Find smallest number with given number of digits and sum of digits under given constraints
- Find the Largest number with given number of digits and sum of digits
- Find smallest number with given number of digits and sum of digits
- Find the sum of the series x(x+y) + x^2(x^2+y^2) +x^3(x^3+y^3)+ ... + x^n(x^n+y^n)
- Find the sum of series 3, 7, 13, 21, 31....
- Find the sum of the series 2, 5, 13, 35, 97...
- Find sum of the series 1-2+3-4+5-6+7.......
- Find last two digits of sum of N factorials
- Find first and last digits of a number
- Given a number n, find the first k digits of n^n
- Program to find the last two digits of x^y
- Find the first and last M digits from K-th power of N
- Program to find last two digits of 2^n