Open In App

Number of digits in the nth number made of given four digits

Improve
Improve
Like Article
Like
Save
Share
Report

Find the number of digits in the nth number constructed by using 6, 1, 4, and 9 as the only digits in the ascending order. First few numbers constructed by using only 6, 1, 4, and 9 as digits in ascending order would be: 

1, 6, 4, 9, 11, 14, 16, 19, 41, 44, 46, 49, 61, 64, 66, 69, 91, 94, 96, 99, 111, 114, 116, 119 and so on. 

Examples: 

Input : 6
Output : 2
6th digit of the series is 14 which has 2 digits.
Input : 21
Output : 3
21st digit of the series is 111 which has 3 digits.

Simple Approach: This is a brute-force approach.
1. Initialize a number to 1 and a counter to 0.
2. Check if the initialized number has only 6, 1, 4, or 9 as its digits.
3. If it has only the mentioned digits then increase the counter by 1. 
4. Increase the number and repeat the above steps until the counter is less than n.
Note: The value of n could be large and hence this approach can’t work as it’s not time efficient.

Time Complexity: O(d * 4^d), where d is the number of digits in the nth number and we need to repeat this process for each possible combination of digits, which is 4^d.

Space Complexity: O(d), where d is the number of digits in the nth number.

Efficient Approach: You can calculate the number of k digit numbers in O (1) time and they will always be the power of 4, for instance, the number of 1-digit numbers in the series would be 4, number of 2-digit numbers in the series would be 16 and so on. 

  1. Count all subsequent k digit numbers and keep adding them to a sum.
  2. Break the loop when the sum is greater than or equal to n.
  3. Maintain a counter to keep track of the number of digits.
  4. The value of the counter at the break of the loop will indicate the answer.

Below is the implementation of the above approach: 

C++




// C++ program to count number of digits
// in n-th number made of given four digits.
 
#include <bits/stdc++.h>
using namespace std;
 
// Efficient function to calculate number
// of digits in the nth number constructed
// by using 6, 1, 4 and 9 as digits in the
// ascending order.
int number_of_digits(int n)
{
    int i, res, sum = 0;
 
    // Number of digits increase after
    // every i-th number where i increases in
    // powers of 4.
    for (i = 4, res = 1;; i *= 4, res++) {
        sum += i;
        if (sum >= n)
            break;
    }
    return res;
}
 
// Driver code
int main()
{
    int n = 21;
    cout << number_of_digits(n) << endl;
    return 0;
}
// Thic code is contributed by Mayank Tyagi


Java




// Java program to count
// number of digits in
// n-th number made of
// given four digits.
import java.io.*;
 
class GFG {
 
    // Efficient function to
    // calculate number of digits
    // in the nth number constructed
    // by using 6, 1, 4 and 9 as
    // digits in the ascending order.
    static int number_of_digits(int n)
    {
        int i;
        int res;
        int sum = 0;
 
        // Number of digits increase
        // after every i-th number
        // where i increases in powers of 4.
        for (i = 4, res = 1;; i *= 4, res++) {
            sum += i;
            if (sum >= n)
                break;
        }
        return res;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int n = 21;
        System.out.println(number_of_digits(n));
    }
}
 
// This code is contributed
// by akt_mit


Python3




# Python3 program to count number of
# digits in n-th number made of given
# four digits.
 
# Efficient function to calculate number
# of digits in the nth number constructed
# by using 6, 1, 4 and 9 as digits in the
# ascending order.
 
 
def number_of_digits(n):
 
    i = 4
    res = 1
    sum = 0
 
    # Number of digits increase after
    # every i-th number where i increases
    # in powers of 4.
    while(True):
        sum += i
        if(sum >= n):
            break
        i *= 4
        res += 1
    return res
 
 
# Driver Code
n = 21
print(number_of_digits(n))
 
# This code is contributed by Pushpesh Raj.


C#




// C#  program to count
// number of digits in
// n-th number made of
// given four digits.
 
using System;
 
public class GFG {
 
    // Efficient function to
    // calculate number of digits
    // in the nth number constructed
    // by using 6, 1, 4 and 9 as
    // digits in the ascending order.
    static int number_of_digits(int n)
    {
        int i;
        int res;
        int sum = 0;
 
        // Number of digits increase
        // after every i-th number
        // where i increases in powers of 4.
        for (i = 4, res = 1;; i *= 4, res++) {
            sum += i;
            if (sum >= n)
                break;
        }
        return res;
    }
 
    // Driver Code
 
    static public void Main()
    {
 
        int n = 21;
        Console.WriteLine(number_of_digits(n));
    }
}


Javascript




<script>
 
// Javascript program to count number of digits
// in n-th number made of given four digits.
 
// Efficient function to calculate number
// of digits in the nth number constructed
// by using 6, 1, 4 and 9 as digits in the
// ascending order.
function number_of_digits(n)
{
    let i, res, sum = 0;
 
    // Number of digits increase after
    // every i-th number where i increases in
    // powers of 4.
    for(i = 4, res = 1;; i *= 4, res++)
    {
        sum += i;
         
        if (sum >= n)
            break;   
    }
    return res;
}
 
// Driver code
let n = 21;
 
document.write(number_of_digits(n) + "<br>");
 
// This code is contributed by Manoj.
 
</script>


PHP




<?php
// PHP program to count number
// of digits in n-th number
// made of given four digits.
 
// Efficient function to
// calculate number of digits
// in the nth number constructed
// by using 6, 1, 4 and 9 as
// digits in the ascending order.
function number_of_digits($n)
{
    $i; $res; $sum = 0;
 
    // Number of digits increase
    // after every i-th number
    // where i increases in
    // powers of 4.
    for ($i = 4, $res = 1;;
         $i *= 4, $res++)
    {
        $sum += $i;
        if ($sum >= $n)
            break;
    }
    return $res;
}
 
// Driver Code
$n = 21;
echo number_of_digits($n),"\n";
     
// This code is contributed by ajit
?>


Output

3













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

Note: Since n could be really large we have used boost library, to know more about boost library give this article a read: Advanced C++ with boost library

Method 3:Efficient and simple code 

Implementation:

C++




#include <bits/stdc++.h>
using namespace std;
 
int countDigits(int n)
{
    // Find the minimum number of digits required
    int k = 1;
    while (pow(4, k) <= n) {
        k++;
    }
 
    // Find the k-digit number in base-4 system
    int d = n - 1;
    int num[k];
    for (int i = k - 1; i >= 0; i--) {
        num[i] = d / pow(4, i);
        d = d % (int)pow(4, i);
    }
 
    // Convert the base-4 number to our system
    string result = "";
    for (int i = 0; i < k; i++) {
        if (num[i] == 0) {
            result += "6";
        }
        else if (num[i] == 1) {
            result += "1";
        }
        else if (num[i] == 2) {
            result += "4";
        }
        else {
            result += "9";
        }
    }
 
    // Count the number of digits in the
      // resulting number
    return result.length();
}
 
// Driver code
int main()
{
    int n = 21;
   
      // Function call
    cout << countDigits(n) << endl;
 
    return 0;
}


Java




import java.util.*;
 
public class Main {
    public static int countDigits(int n) {
        // Find the minimum number of digits required
        int k = 1;
        while (Math.pow(4, k) <= n) { // Find the smallest k such that 4^k is greater than n
            k++;
        }
 
        // Calculate the digits of the resulting number
        int d = n - 1;
        int[] num = new int[k]; // Array to store the digits
        for (int i = k - 1; i >= 0; i--) {
            num[i] = d / (int) Math.pow(4, i); // Divide d by 4^i and store the quotient in num[i]
            d = d % (int) Math.pow(4, i); // Update d to the remainder after division
        }
 
        // Build the resulting number as a string
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < k; i++) {
            if (num[i] == 0) {
                result.append("6"); // If the digit is 0, append "6"
            } else if (num[i] == 1) {
                result.append("1"); // If the digit is 1, append "1"
            } else if (num[i] == 2) {
                result.append("4"); // If the digit is 2, append "4"
            } else {
                result.append("9"); // If the digit is 3, append "9"
            }
        }
 
        // Count the number of digits in the resulting number
        return result.length();
    }
 
    public static void main(String[] args) {
        int n = 21;
 
        // Function call
        System.out.println(countDigits(n));
    }
}


Python3




def count_digits(n):
    # Find the minimum number of digits required
    k = 1
    while 4 ** k <= n:
        k += 1
 
    # Find the k-digit number in the base-4 system
    d = n - 1
    num = [0] * k
    for i in range(k - 1, -1, -1):
        num[i] = d // (4 ** i)
        d = d % (4 ** i)
 
    # Convert the base-4 number to our system
    result = ""
    for i in range(k):
        if num[i] == 0:
            result += "6"
        elif num[i] == 1:
            result += "1"
        elif num[i] == 2:
            result += "4"
        else:
            result += "9"
 
    # Count the number of digits in the resulting number
    return len(result)
 
# Driver code
if __name__ == "__main__":
    n = 21
 
    # Function call
    print(count_digits(n))


C#




// C# code
using System;
using System.Text;
 
public class GFG
{
    public static int CountDigits(int n)
    {
        // Find the minimum number of digits required
        int k = 1;
        while (Math.Pow(4, k) <= n)
        // Find the smallest k such that 4^k is greater than n
            k++;
        }
 
        // Calculate the digits of the resulting number
        int d = n - 1;
        int[] num = new int[k]; // Array to store the digits
        for (int i = k - 1; i >= 0; i--)
        {
            num[i] = d / (int)Math.Pow(4, i); // Divide d by 4^i and store the quotient in num[i]
            d = d % (int)Math.Pow(4, i); // Update d to the remainder after division
        }
 
        // Build the resulting number as a string
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < k; i++)
        {
            if (num[i] == 0)
            {
                result.Append("6"); // If the digit is 0, append "6"
            }
            else if (num[i] == 1)
            {
                result.Append("1"); // If the digit is 1, append "1"
            }
            else if (num[i] == 2)
            {
                result.Append("4"); // If the digit is 2, append "4"
            }
            else
            {
                result.Append("9"); // If the digit is 3, append "9"
            }
        }
 
        // Count the number of digits in the resulting number
        return result.Length;
    }
 
    public static void Main(string[] args)
    {
        int n = 21;
 
        // Function call
        Console.WriteLine(CountDigits(n));
    }
}
 
// This code is contributed by Utkarsh Kumar


Javascript




function countDigits(n) {
    // Find the minimum number of digits required
    let k = 1;
    while (Math.pow(4, k) <= n) {
        k++;
    }
 
    // Find the k-digit number in base-4 system
    let d = n - 1;
    let num = new Array(k);
    for (let i = k - 1; i >= 0; i--) {
        num[i] = Math.floor(d / Math.pow(4, i));
        d = d % Math.pow(4, i);
    }
 
    // Convert the base-4 number to our system
    let result = "";
    for (let i = 0; i < k; i++) {
        if (num[i] === 0) {
            result += "6";
        } else if (num[i] === 1) {
            result += "1";
        } else if (num[i] === 2) {
            result += "4";
        } else {
            result += "9";
        }
    }
 
    // Count the number of digits in the resulting number
    return result.length;
}
 
// Driver code
let n = 21;
console.log(countDigits(n));


Output

3













Time Complexity: O(logn)
Auxiliary Space: O(logn)

Approach:

  • Initialize a variable digitsCount as 1, which represents the number of digits in the constructed numbers.
  • Initialize a variable count as 0, which represents the count of numbers constructed so far.
  • Iterate while count is less than or equal to n.
  • Increment digitsCount by 1.
  • Calculate the number of numbers that can be constructed with digitsCount digits using the given digits (6, 1, 4, and 9) as the only digits in the ascending order. This can be calculated as (pow(4, digitsCount) – pow(4, digitsCount – 1)).
  • Increment count by the calculated number of numbers.
  • The number of digits in the n-th number will be digitsCount.
  • Return digitsCount.

Below is the implementation of the above approach:

C++




#include <iostream>
#include <cmath>
using namespace std;
 
int numberOfDigits(int n) {
    int digitsCount = 1;
    int count = 0;
 
    while (count <= n) {
        digitsCount++;
        count += pow(4, digitsCount) - pow(4, digitsCount - 1);
    }
 
    return digitsCount ;
}
 
int main() {
    int n = 21;
    int digits = numberOfDigits(n);
    cout << digits << endl;
    return 0;
}


Java




import java.util.*;
 
public class NumberOfDigits {
 
    public static int numberOfDigits(int n) {
        int digitsCount = 1;
        int count = 0;
 
        while (count <= n) {
            digitsCount++;
            count += Math.pow(4, digitsCount) - Math.pow(4, digitsCount - 1);
        }
 
        return digitsCount;
    }
 
    public static void main(String[] args) {
        int n = 21;
        int digits = numberOfDigits(n);
        System.out.println(digits);
    }
}


Python3




import math
 
def number_of_digits(n):
    digits_count = 1
    count = 0
 
    # Keep calculating the number of digits until count exceeds or equals n
    while count <= n:
        digits_count += 1
        count += math.pow(4, digits_count) - math.pow(4, digits_count - 1)
 
    return digits_count
 
def main():
    n = 21
    digits = number_of_digits(n)
    print(digits)
 
if __name__ == "__main__":
    main()


C#




using System;
 
class Program
{
    static int NumberOfDigits(int n)
    {
        int digitsCount = 1;
        int count = 0;
 
        // Loop until the count exceeds the given number n
        while (count <= n)
        {
            // Increment the number of digits
            digitsCount++;
 
            // Update the count using the formula for the sum of a geometric series
            count += (int)(Math.Pow(4, digitsCount) - Math.Pow(4, digitsCount - 1));
        }
 
        // Return the final number of digits
        return digitsCount;
    }
 
    static void Main()
    {
        // Test case with n = 21
        int n = 21;
         
        // Call the function to calculate the number of digits
        int digits = NumberOfDigits(n);
 
        // Print the result
        Console.WriteLine(digits);
    }
}


Javascript




function numberOfDigits(n) {
    let digitsCount = 1;
    let count = 0;
 
    while (count <= n) {
        digitsCount++;
        // Calculate the count for the next digit using powers of 4
        count += Math.pow(4, digitsCount) - Math.pow(4, digitsCount - 1);
    }
 
    return digitsCount;
}
 
// Example usage
const n = 21;
const digits = numberOfDigits(n);
console.log(digits);


Output

3














Time Complexity:  O(log N), where N is the given input number.

Auxiliary Space: O(1), it requires a constant amount of additional space.



Last Updated : 27 Nov, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads