Wednesday, July 3, 2024
HomeData ModellingData Structure & AlgorithmFind n-th element in a series with only 2 digits (4 and...

Find n-th element in a series with only 2 digits (4 and 7) allowed | Set 2 (log(n) method)

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.
Examples: 
 

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. 
 

C++




// C++ program to find n-th number containing
// only 4 and 7.
#include<bits/stdc++.h>
using namespace std;
 
string findNthNo(int n)
{
    string res = "";
    while (n >= 1)
    {
        // If n is odd, append 4 and
        // move to parent
        if (n & 1)
        {
            res = res + "4";
            n = (n-1)/2;       
        }
 
        // If n is even, append 7 and
        // move to parent
        else
        {
            res = res + "7";
            n = (n-2)/2;     
        }
    }
 
   // Reverse res and return.
   reverse(res.begin(), res.end());
   return res;
}
 
// Driver code
int main()
{
    int n = 13;
    cout << findNthNo(n);
    return 0;
}


Java




// java program to find n-th number
// containing only 4 and 7.
public class GFG {
     
    static String findNthNo(int n)
    {
        String res = "";
        while (n >= 1)
        {
             
            // If n is odd, append
            // 4 and move to parent
            if ((n & 1) == 1)
            {
                res = res + "4";
                n = (n - 1) / 2;    
            }
     
            // If n is even, append
            // 7 and move to parent
            else
            {
                res = res + "7";
                n = (n - 2) / 2;    
            }
        }
     
        // Reverse res and return.
        StringBuilder sb =
            new StringBuilder(res);
        sb.reverse();
        return new String(sb);
    }
     
    // Driver code
    public static void main(String args[])
    {
        int n = 13;
     
        System.out.print( findNthNo(n) );
    }
}
 
// This code is contributed by Sam007


Python3




# Python3 program to find
# n-th number containing
# only 4 and 7.
def reverse(s):
    if len(s) == 0:
        return s
    else:
        return reverse(s[1:]) + s[0]
         
def findNthNo(n):
    res = "";
    while (n >= 1):
         
        # If n is odd, append
        # 4 and move to parent
        if (n & 1):
            res = res + "4";
            n = (int)((n - 1) / 2);
             
            # If n is even, append7
            # and move to parent
        else:
            res = res + "7";
            n = (int)((n - 2) / 2);
             
    # Reverse res
    # and return.
    return reverse(res);
 
# Driver code
n = 13;
print(findNthNo(n));
 
# This code is contributed
# by mits


C#




// C# program to find n-th number
// containing only 4 and 7.
using System;
class GFG {
 
static string findNthNo(int n)
{
    string res = "";
    while (n >= 1)
    {
         
        // If n is odd, append 4 and
        // move to parent
        if ((n & 1) == 1)
        {
            res = res + "4";
            n = (n - 1) / 2;    
        }
 
        // If n is even, append 7 and
        // move to parent
        else
        {
            res = res + "7";
            n = (n - 2) / 2;    
        }
    }
 
    // Reverse res and return.
    char[] arr = res.ToCharArray();
    Array.Reverse(arr);
    return new string(arr);
 
}
 
// Driver Code
public static void Main()
{
        int n = 13;
        Console.Write( findNthNo(n) );
}
}
 
// This code is contributed by Sam007


PHP




<?php
// PHP program to find
// n-th number containing
// only 4 and 7.
 
function findNthNo($n)
{
    $res = "";
    while ($n >= 1)
    {
        // If n is odd, append
        // 4 and move to parent
        if ($n & 1)
        {
            $res = $res . "4";
            $n = (int)(($n - 1) / 2);
        }
 
        // If n is even, append
        // 7 and move to parent
        else
        {
            $res = $res . "7";
            $n = (int)(($n - 2) / 2);
        }
    }
     
// Reverse res
// and return.
return strrev($res);
}
 
// Driver code
$n = 13;
echo findNthNo($n);
 
// This code is contributed
// by mits
?>


Javascript




<script>
 
// javascript program to find n-th number
// containing only 4 and 7.
     
function findNthNo(n)
{
res = "";
while (n >= 1)
{
 
// If n is odd, append
// 4 and move to parent
if ((n & 1) == 1)
{
res = res + "4";
n = (n - 1) / 2;    
}
 
// If n is even, append
// 7 and move to parent
else
{
res = res + "7";
n = parseInt((n - 2) / 2);    
}
}
 
// Reverse res and return.
return res.split("").reverse().join("");
}
 
// Driver code
var n = 13;
 
document.write( findNthNo(n) );
 
// This code is contributed by 29AjayKumar
 
</script>


Output:  

774

Time Complexity: O(logN), where N represents the given integer.
Auxiliary Space: O(1), no extra space is required, so it is a constant.

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 neveropen and would like to contribute, you can also write an article using write.neveropen.co.za or mail your article to review-team@neveropen.co.za. See your article appearing on the neveropen 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.
 

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

Nokonwaba Nkukhwana
Experience as a skilled Java developer and proven expertise in using tools and technical developments to drive improvements throughout a entire software development life cycle. I have extensive industry and full life cycle experience in a java based environment, along with exceptional analytical, design and problem solving capabilities combined with excellent communication skills and ability to work alongside teams to define and refine new functionality. Currently working in springboot projects(microservices). Considering the fact that change is good, I am always keen to new challenges and growth to sharpen my skills.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments