Comprobar si el producto de cada subsecuencia contigua es diferente o no en un número

Dado un número entero N , la tarea es verificar si el producto de cada conjunto consecutivo de dígitos es distinto o no.

Ejemplos: 

Entrada: N = 234 
Salida: Sí 
 

Establecer Producto
{2} 2
{2, 3} 2 * 3 = 6
{2, 3, 4} 2 * 3 * 4 = 24
{3} 3
{3, 4} 3 * 4 = 12
{4} 4

Todos los productos son distintos.

Entrada: N = 1234 
Salida: No 
Establezca {1, 2} y {2} ambos del mismo producto, es decir, 2. 
 

Método: almacenar el producto de dígitos de cada subsecuencia contigua en un conjunto . Si el producto que se va a insertar ya está presente en el conjunto en algún momento, la respuesta es «No», de lo contrario, todos los productos son distintos al final.

A continuación se muestra la implementación del enfoque anterior:  

C++

// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function that returns true if the product
// of every digit of a contiguous subsequence
// is distinct
bool productsDistinct(int N)
{
    // To store the given number as a string
    string s = "";
 
    // Append all the digits
    // starting from the end
    while (N) {
        s += (char)(N % 10 + '0');
        N /= 10;
    }
 
    // Reverse the string to get
    // the  original number
    reverse(s.begin(), s.end());
 
    // Store size of the string
    int sz = s.size();
 
    // Set to store product of
    // each contiguous subsequence
    set<int> se;
 
    // Find product of every
    // contiguous subsequence
    for (int i = 0; i < sz; i++) {
        int product = 1;
        for (int j = i; j < sz; j++) {
            product *= (int)(s[j] - '0');
 
            // If current product already
            // exists in the set
            if (se.find(product) != se.end())
                return false;
            else
                se.insert(product);
        }
    }
 
    return true;
}
 
// Driver code
int main()
{
    int N = 2345;
 
    if (productsDistinct(N))
        cout << "Yes";
    else
        cout << "No";
 
    return 0;
}

Java

// Java implementation of the approach
import java.util.*;
 
class GFG
{
 
// Function that returns true if
// the product of every digit of a
// contiguous subsequence is distinct
static boolean productsDistinct(int N)
{
     
    // To store the given number
    // as a string
    String s = "";
 
    // Append all the digits
    // starting from the end
    while (N > 0)
    {
        s += (char)(N % 10 + '0');
        N /= 10;
    }
 
    // Reverse the string to get
    // the original number
    s = reverse(s);
 
    // Store size of the string
    int sz = s.length();
 
    // Set to store product of
    // each contiguous subsequence
    HashSet<Integer> se = new HashSet<Integer>();
 
    // Find product of every
    // contiguous subsequence
    for (int i = 0; i < sz; i++)
    {
        int product = 1;
        for (int j = i; j < sz; j++)
        {
            product *= (int)(s.charAt(j) - '0');
 
            // If current product already
            // exists in the set
            if (se.contains(product))
                return false;
            else
                se.add(product);
        }
    }
    return true;
}
 
static String reverse(String input)
{
    char[] a = input.toCharArray();
    int l, r;
    r = a.length - 1;
    for (l = 0; l < r; l++, r--)
    {
        // Swap values of l and r
        char temp = a[l];
        a[l] = a[r];
        a[r] = temp;
    }
    return String.valueOf(a);
}
 
// Driver code
public static void main(String[] args)
{
    int N = 2345;
 
    if (productsDistinct(N))
        System.out.println("Yes");
    else
        System.out.println("No");
    }
}
 
// This code is contributed
// by PrinciRaj1992

Python3

# Python 3 implementation of the approach
 
# Function that returns true if the product
# of every digit of a contiguous subsequence
# is distinct
 
 
def productsDistinct(A):
    A = str(A)
    n = len(A)
    hs = set()
    for i in range(n):
        prod = 1
        for j in range(i, n):
            prod = prod * int(A[j])
            if(prod in hs):
                return False
            else:
                hs.add(prod)
    return True
 
 
# Driver code
if __name__ == '__main__':
    N = 2345
 
    if (productsDistinct(N)):
        print("Yes")
    else:
        print("No")
 
# This code is contributed by
# Surendra_Gangwar

C#

// C# implementation of the approach
using System;
using System.Collections.Generic;
 
class GFG
{
 
// Function that returns true if
// the product of every digit of a
// contiguous subsequence is distinct
static Boolean productsDistinct(int N)
{
     
    // To store the given number
    // as a string
    String s = "";
 
    // Append all the digits
    // starting from the end
    while (N > 0)
    {
        s += (char)(N % 10 + '0');
        N /= 10;
    }
 
    // Reverse the string to get
    // the original number
    s = reverse(s);
 
    // Store size of the string
    int sz = s.Length;
 
    // Set to store product of
    // each contiguous subsequence
    HashSet<int> se = new HashSet<int>();
 
    // Find product of every
    // contiguous subsequence
    for (int i = 0; i < sz; i++)
    {
        int product = 1;
        for (int j = i; j < sz; j++)
        {
            product *= (int)(s[j] - '0');
 
            // If current product already
            // exists in the set
            if (se.Contains(product))
                return false;
            else
                se.Add(product);
        }
    }
    return true;
}
 
static String reverse(String input)
{
    char[] a = input.ToCharArray();
    int l, r;
    r = a.Length - 1;
    for (l = 0; l < r; l++, r--)
    {
        // Swap values of l and r
        char temp = a[l];
        a[l] = a[r];
        a[r] = temp;
    }
    return String.Join("",a);
}
 
// Driver code
public static void Main(String[] args)
{
    int N = 2345;
 
    if (productsDistinct(N))
        Console.WriteLine("Yes");
    else
        Console.WriteLine("No");
}
}
 
// This code is contributed by 29AjayKumar

Javascript

<script>
 
// Javascript implementation of the approach
 
// Function that returns true if the product
// of every digit of a contiguous subsequence
// is distinct
function productsDistinct(N)
{
     
    // To store the given number as a string
    var s = "";
 
    // Append all the digits
    // starting from the end
    while (N)
    {
        s += String.fromCharCode(
            N % 10 + '0'.charCodeAt(0));
        N = parseInt(N / 10);
    }
 
    // Reverse the string to get
    // the  original number
    s = s.split('').reverse().join('');
 
    // Store size of the string
    var sz = s.length;
 
    // Set to store product of
    // each contiguous subsequence
    var se = new Set();
 
    // Find product of every
    // contiguous subsequence
    for(var i = 0; i < sz; i++)
    {
        var product = 1;
        for(var j = i; j < sz; j++)
        {
            product *= (s[j].charCodeAt(0) -
                         '0'.charCodeAt(0));
 
            // If current product already
            // exists in the set
            if (se.has(product))
                return false;
            else
                se.add(product);
        }
    }
    return true;
}
 
// Driver code
var N = 2345;
if (productsDistinct(N))
    document.write("Yes");
else
    document.write("No");
 
// This code is contributed by rrrtnx
 
</script>
Producción: 

Yes

 

Complejidad del tiempo: O((log 10 N) 2 *log(log 10 N))

Espacio Auxiliar: O((log 10 N) 2 )

Publicación traducida automáticamente

Artículo escrito por pawan_asipu 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 *