Encuentre el número n-ésimo formado solo por dígitos pares

Dado un número n, encuentre el n-ésimo número positivo formado solo por dígitos pares (0, 2, 4, 6, 8). Los primeros números hechos de dígitos pares son 0, 2, 4, 6, 8, 20, 22, 24…….

Ejemplos: 

Input  : 2
Output : 2
Second number made of 0, 2, 4, 6, 8 is 2

Input  : 10
Output : 28

Enfoque 
ingenuo Un enfoque ingenuo es comenzar desde 0 y verificar si está compuesto solo de {0, 2, 4, 6, 8} y detenerse cuando encuentre el n-ésimo número.  

C++

// Simple C++ program to find
// n-th number made of even
// digits only
#include<bits/stdc++.h>
using namespace std;
 
// function to calculate nth
// number made of even digits only
int findNthEvenDigitNumber(int n )
{
    // variable to note how
    // many such numbers have
    // been found till now
    int count = 0;
    for (int i = 0 ; ; i++)
    {
        int curr = i;
 
        // bool variable to check if
        // 1, 3, 5, 7, 9 is there or not
        bool isCurrEvenDigit = true ;
 
        // checking each digit
        // of the number
        while (curr != 0)
        {
            // If 1, 3, 5, 7, 9 is found
            // temp is changed to false
            if (curr % 10 == 1 || curr % 10 == 3 ||
                curr % 10 == 5 || curr % 10 == 7 ||
                curr % 10 == 9)
                isCurrEvenDigit = false;
            curr = curr / 10;
        }
 
        // temp is true it means that it
        // does not have 1, 3, 5, 7, 9
        if (isCurrEvenDigit == true)
            count++;
 
        // If nth such number is
        // found return it
        if (count == n)
            return i;
    }
}
 
// Driver Code
int main()
{
    cout << findNthEvenDigitNumber(2)
         << endl;
    cout << findNthEvenDigitNumber(10)
         << endl;
    return 0;
}

Java

// Simple Java program to
// find the n-th number made
// of even digits only
 
class GFG
{
    // function to calculate nth
    // number made of even digits only
    static int findNthEvenDigitNumber(int n )
    {
        // variable to note how
        // many such numbers have
        // been found till now
        int count = 0;
        for (int i = 0 ; ; i++)
        {
            int curr = i;
     
            // bool variable to check if
            // 1, 3, 5, 7, 9 is there or not
            boolean isCurrEvenDigit = true ;
     
            // checking each digit
            // of the number
            while (curr != 0)
            {
                // If 1, 3, 5, 7, 9 is found
                // temp is changed to false
                if (curr % 10 == 1 || curr % 10 == 3 ||
                    curr % 10 == 5 || curr % 10 == 7 ||
                    curr % 10 == 9)
                    isCurrEvenDigit = false;
                curr = curr / 10;
            }
     
            // temp is true it means that it
            // does not have 1, 3, 5, 7, 9
            if (isCurrEvenDigit == true)
                count++;
     
            // If nth such number
            // is found return it
            if (count == n)
                return i;
        }
    }
     
    // Driver Code
    public static void main (String[] args)
    {
        System.out.println(findNthEvenDigitNumber(2));
        System.out.println(findNthEvenDigitNumber(10));
    }
}

Python3

# Simple Python3 program to find nth
# number made of even digits only
 
# function to calculate nth number
# made of even digits only
def findNthEvenDigitNumber(n):
 
    # variable to note how many such
    # numbers have been found till now
    count = 0;
    i = 0;
    while (True):
     
        curr = i;
 
        # bool variable to check if
        # 1, 3, 5, 7, 9 is there or not
        isCurrEvenDigit = True;
 
        # checking each digit of the number
        while (curr != 0):
             
            # If 1, 3, 5, 7, 9 is found
            # temp is changed to false
            if (curr % 10 == 1 or curr % 10 == 3 or
                curr % 10 == 5 or curr % 10 == 7 or
                curr % 10 == 9):
                isCurrEvenDigit = False;
            curr = curr // 10;
 
        # temp is true it means that it
        # does not have 1, 3, 5, 7, 9
        if (isCurrEvenDigit == True):
            count += 1;
 
        # If nth such number is found,
        # return it
        if (count == n):
            return i;
         
        i += 1;
 
# Driver Code
print(findNthEvenDigitNumber(2));
print(findNthEvenDigitNumber(10));
 
# This code is contributed by mits

C#

// Simple C# program to
// find the n-th number
// made of even digits only
using System;
 
class GFG
{
    // function to calculate nth
    // number made of even digits only
    static int findNthEvenDigitNumber(int n )
    {
        // variable to note how
        // many such numbers have
        // been found till now
        int count = 0;
        for (int i = 0 ; ; i++)
        {
            int curr = i;
     
            // bool variable to check if
            // 1, 3, 5, 7, 9 is there or not
            bool isCurrEvenDigit = true ;
     
            // checking each digit
            // of the number
            while (curr != 0)
            {
                // If 1, 3, 5, 7, 9 is found
                // temp is changed to false
                if (curr % 10 == 1 || curr % 10 == 3 ||
                    curr % 10 == 5 || curr % 10 == 7 ||
                    curr % 10 == 9 )
                    isCurrEvenDigit = false;
                curr = curr / 10;
            }
     
            // temp is true it means that it
            // does not have 1, 3, 5, 7, 9
            if (isCurrEvenDigit == true)
                count++;
     
            // If nth such number
            // is found return it
            if (count == n)
                return i;
        }
    }
     
    // Driver code
    public static void Main ()
    {
        Console.WriteLine(findNthEvenDigitNumber(2));
        Console.WriteLine(findNthEvenDigitNumber(10));
    }
}
 
// This article is contributed by vt_m.

PHP

<?php
// Simple C++ program to find
// nth number made of even
// digits only
 
 
// function to calculate nth
// number made of even digits only
function findNthEvenDigitNumber($n )
{
    // variable to note how
    // many such numbers have
    // been found till now
    $count = 0;
    for ($i = 0 ; ; $i++)
    {
        $curr = $i;
 
        // bool variable to check if
        // 1, 3, 5, 7, 9 is there or not
        $isCurrEvenDigit = true ;
 
        // checking each digit
        // of the number
        while ($curr != 0)
        {
            // If 1, 3, 5, 7, 9 is found
            // temp is changed to false
            if ($curr % 10 == 1 || $curr % 10 == 3 ||
                $curr % 10 == 5 || $curr % 10 == 7 ||
                $curr % 10 == 9)
                $isCurrEvenDigit = false;
            $curr = $curr / 10;
        }
 
        // temp is true it means that it
        // does not have 1, 3, 5, 7, 9
        if ($isCurrEvenDigit == true)
            $count++;
 
        // If nth such number
        // is found return it
        if ($count == $n)
            return $i;
    }
}
 
// Driver Code
echo findNthEvenDigitNumber(2),"\n" ;
echo findNthEvenDigitNumber(10) ;
 
// This code is contributed by nitin mittal
?>

Javascript

<script>
 
// Simple JavaScript program to find
// n-th number made of even
// digits only
 
// Function to calculate nth
// number made of even digits only
function findNthEvenDigitNumber(n)
{
     
    // Variable to note how
    // many such numbers have
    // been found till now
    let count = 0;
     
    for(let i = 0;; i++)
    {
        let curr = i;
 
        // Bool variable to check if
        // 1, 3, 5, 7, 9 is there or not
        let isCurrEvenDigit = true;
 
        // Checking each digit
        // of the number
        while (curr != 0)
        {
             
            // If 1, 3, 5, 7, 9 is found
            // temp is changed to false
            if (curr % 10 == 1 || curr % 10 == 3 ||
                curr % 10 == 5 || curr % 10 == 7 ||
                curr % 10 == 9)
                isCurrEvenDigit = false;
                 
            curr = Math.floor(curr / 10);
        }
 
        // temp is true it means that it
        // does not have 1, 3, 5, 7, 9
        if (isCurrEvenDigit === true)
            count++;
 
        // If nth such number is
        // found return it
        if (count === n)
            return i;
    }
}
 
// Driver Code
document.write(findNthEvenDigitNumber(2) + "<br>");
document.write(findNthEvenDigitNumber(10) + "<br>");
 
// This code is contributed by Manoj.
 
</script>

Producción : 

2
28

Complejidad de tiempo: O(n * log 10 n), donde n representa el entero dado.
Espacio auxiliar: O(1), no se requiere espacio adicional, por lo que es una constante.
Enfoque eficiente 
Necesitamos encontrar números hechos de 5 dígitos, 0, 2, 4, 6 y 8. Cuando convertimos un número en un número de base 5, solo estará hecho de números {0, 1, 2, 3, 4} . Se puede ver claramente que cada dígito en el conjunto de dígitos requerido {0, 2, 4, 6, 8} es el doble del dígito en el índice correspondiente del conjunto de dígitos de base 5. Entonces, para encontrar el número n-ésimo compuesto solo por dígitos pares, siga los pasos mencionados a continuación
. Paso 1: Convierta n en n-1, esto se hace para excluir el cero. 
Paso 2: Convierta n en un número decimal de base 5. 
Paso 3: Multiplique el número encontrado arriba por 2. Este es el número requerido

C++

// Efficient C++ program to
// find n-th number made of
// even digits only
#include<bits/stdc++.h>
using namespace std;
 
// function to find nth number
// made of even digits only
int findNthEvenDigitNumber(int n)
{
    // If n=1 return 0
    if (n == 1)
        return 0;
 
    // vector to store the digits
    // when converted into base 5
    vector< int> v;
 
    // Reduce n to n-1 to exclude 0
    n = n - 1;
  
    // Reduce n to base 5
    // number and store digits
    while (n > 0)
    {
        // pushing the digits
        // into vector
        v.push_back(n % 5);
        n = n / 5;
    }
 
    // variable to represent the
    // number after converting it
    // to base 5. Since the digits
    // are be in reverse order,
    // we traverse vector from back
    int result = 0;
    for (int i = v.size() - 1; i >= 0; i--)
    {
        result = result * 10;
        result = result + v[i];
    }
 
    // return 2*result (to convert
    // digits 0, 1, 2, 3, 4 to
    // 0, 2, 4, 6, 8.
    return 2*result;
}
 
// Driver Code
int main()
{
    cout << findNthEvenDigitNumber(2)
         << endl;
    cout << findNthEvenDigitNumber(10)
         << endl;
    return 0;
}

Java

import java.util.*;
// Efficient Java program to
// find n-th number made of
// even digits only
 
class GFG {
 
// function to find nth number
// made of even digits only
    static int findNthEvenDigitNumber(int n) {
        // If n=1 return 0
        if (n == 1) {
            return 0;
        }
 
        // vector to store the digits
        // when converted into base 5
        Vector< Integer> v = new Vector<>();
 
        // Reduce n to n-1 to exclude 0
        n = n - 1;
 
        // Reduce n to base 5
        // number and store digits
        while (n > 0) {
            // pushing the digits
            // into vector
            v.add(n % 5);
            n = n / 5;
        }
 
        // variable to represent the
        // number after converting it
        // to base 5. Since the digits
        // are be in reverse order,
        // we traverse vector from back
        int result = 0;
        for (int i = v.size() - 1; i >= 0; i--) {
            result = result * 10;
            result = result + v.get(i);
        }
 
        // return 2*result (to convert
        // digits 0, 1, 2, 3, 4 to
        // 0, 2, 4, 6, 8.
        return 2 * result;
    }
 
// Driver Code
    public static void main(String[] args) {
        System.out.println(findNthEvenDigitNumber(2));
        System.out.println(findNthEvenDigitNumber(10));
    }
}
// This code is contributed by PrinciRaj1992

Python3

# Efficient Python 3 program to find n-th
# number made of even digits only
 
# function to find nth number made of
# even digits only
def findNthEvenDigitNumber( n):
 
    # If n = 1 return 0
    if (n == 1):
        return 0
 
    # vector to store the digits
    # when converted into base 5
    v = []
 
    # Reduce n to n-1 to exclude 0
    n = n - 1
 
    # Reduce n to base 5 number and
    # store digits
    while (n > 0):
         
        # pushing the digits into vector
        v.append(n % 5)
        n = n // 5
 
    # variable to represent the number 
    # after converting it to base 5.
    # Since the digits are be in reverse
    # order, we traverse vector from back
    result = 0
    for i in range(len(v) - 1, -1, -1):
        result = result * 10
        result = result + v[i]
 
    # return 2*result (to convert
    # digits 0, 1, 2, 3, 4 to
    # 0, 2, 4, 6, 8.
    return 2 * result
 
# Driver Code
if __name__ == "__main__":
     
    print(findNthEvenDigitNumber(2))
    print(findNthEvenDigitNumber(10))
 
# This code is contributed by ita_c

C#

// Efficient C# program to
// find n-th number made of
// even digits only
using System;
using System.Collections;
 
class GFG {
 
    // function to find nth number
    // made of even digits only
    static int findNthEvenDigitNumber(int n)
    {
        // If n=1 return 0
        if (n == 1)
        {
            return 0;
        }
 
        // vector to store the digits
        // when converted into base 5
        ArrayList v = new ArrayList();
 
        // Reduce n to n-1 to exclude 0
        n = n - 1;
 
        // Reduce n to base 5
        // number and store digits
        while (n > 0)
        {
            // pushing the digits
            // into vector
            v.Add(n % 5);
            n = n / 5;
        }
 
        // variable to represent the
        // number after converting it
        // to base 5. Since the digits
        // are be in reverse order,
        // we traverse vector from back
        int result = 0;
        for (int i = v.Count - 1; i >= 0; i--)
        {
            result = result * 10;
            result = result + (int)v[i];
        }
 
        // return 2*result (to convert
        // digits 0, 1, 2, 3, 4 to
        // 0, 2, 4, 6, 8.
        return 2 * result;
    }
 
    // Driver Code
    public static void Main()
    {
        Console.WriteLine(findNthEvenDigitNumber(2));
        Console.WriteLine(findNthEvenDigitNumber(10));
    }
}
 
// This code is contributed by 29AjayKumar

PHP

<?php
// Efficient PHP program to find n-th
// number made of even digits only
 
// function to find nth number
// made of even digits only
function findNthEvenDigitNumber($n)
{
    // If n=1 return 0
    if ($n == 1)
        return 0;
 
    // vector to store the digits
    // when converted into base 5
    $v = array();
 
    // Reduce n to n-1 to exclude 0
    $n = $n - 1;
 
    // Reduce n to base 5
    // number and store digits
    while ($n > 0)
    {
        // pushing the digits
        // into vector
        array_push($v, $n % 5);
        $n = (int)($n / 5);
    }
 
    // variable to represent the number
    // after converting it to base 5.
    // Since the digits are be in
    // reverse order, we traverse vector
    // from back
    $result = 0;
    for ($i = count($v) - 1; $i >= 0; $i--)
    {
        $result = $result * 10;
        $result = $result + $v[$i];
    }
 
    // return 2*result (to convert
    // digits 0, 1, 2, 3, 4 to
    // 0, 2, 4, 6, 8.
    return 2 * $result;
}
 
// Driver Code
echo findNthEvenDigitNumber(2) . "\n";
echo findNthEvenDigitNumber(10) . "\n"
 
// This code is contributed by mits
?>

Javascript

<script>
// Efficient Javascript program to
// find n-th number made of
// even digits only
     
    // function to find nth number
    // made of even digits only
    function findNthEvenDigitNumber(n)
    {
        // If n=1 return 0
        if (n == 1) {
            return 0;
        }
  
        // vector to store the digits
        // when converted into base 5
        let v = [];
  
        // Reduce n to n-1 to exclude 0
        n = n - 1;
  
        // Reduce n to base 5
        // number and store digits
        while (n > 0) {
            // pushing the digits
            // into vector
            v.push(n % 5);
            n = Math.floor(n / 5);
        }
  
        // variable to represent the
        // number after converting it
        // to base 5. Since the digits
        // are be in reverse order,
        // we traverse vector from back
        let result = 0;
        for (let i = v.length - 1; i >= 0; i--) {
            result = result * 10;
            result = result + v[i];
        }
  
        // return 2*result (to convert
        // digits 0, 1, 2, 3, 4 to
        // 0, 2, 4, 6, 8.
        return 2 * result;
    }
     
    // Driver Code
    document.write(findNthEvenDigitNumber(2)+"<br>");
    document.write(findNthEvenDigitNumber(10));
     
    // This code is contributed by rag2127
</script>

Producción : 

2
28

Complejidad de tiempo: O (log 5 (n)), donde n es el número entero dado.

Espacio auxiliar: O(log 5 (n)), donde n es el entero dado.

Este artículo es una contribución de Ayush Jha . Si le gusta GeeksforGeeks y le gustaría contribuir, también puede escribir un artículo usando contribuya.geeksforgeeks.org o envíe su artículo por correo a review-team@geeksforgeeks.org. Vea su artículo que aparece en la página principal de GeeksforGeeks y ayude a otros Geeks.
Escriba comentarios si encuentra algo incorrecto o si desea compartir más información sobre el tema tratado anteriormente.
 

Publicación traducida automáticamente

Artículo escrito por GeeksforGeeks-1 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *