Dada una array arr de tamaño N , la tarea es contar el número de índices j (j<i) tales que a[i] divide a[j] , para todos los índices válidos i .
Ejemplos:
Entrada: arr[] = {8, 1, 28, 4, 2, 6, 7}
Salida: 0, 1, 0, 2, 3, 0, 1
Número de múltiplos para cada elemento antes de sí mismo –
N(8) = 0()
N(1) = 1 (8)
N(28) = 0()
N(4) = 2 (28, 8)
N(2) = 3 (4, 28, 8)
N(6) = 0()
N(7) = 1 (28)
Entrada: arr[] = {1, 1, 1, 1}
Salida: 0, 1, 2, 3
Enfoque ingenuo: atravesar todos los índices válidos j, en el rango [0, i-1], para cada índice i ; y cuente los divisores para cada índice.
Complejidad de tiempo: O(N 2 )
Complejidad de espacio: O(1)
Enfoque eficiente: Este enfoque consiste en utilizar map . Incremente el conteo de factores en el mapa mientras recorre la array y busque ese conteo en el mapa para encontrar todos los j (<i) válidos sin regresar.
A continuación se muestra la implementación del enfoque anterior.
C++
// C++ program to count of multiples // in an Array before every element #include <bits/stdc++.h> using namespace std; // Function to find all factors of N // and keep their count in map void add_factors(int n, unordered_map<int, int>& mp) { // Traverse from 1 to sqrt(N) // if i divides N, // increment i and N/i in map for (int i = 1; i <= int(sqrt(n)); i++) { if (n % i == 0) { if (n / i == i) mp[i]++; else { mp[i]++; mp[n / i]++; } } } } // Function to count of multiples // in an Array before every element void count_divisors(int a[], int n) { // To store factors all of all numbers unordered_map<int, int> mp; // Traverse for all possible i's for (int i = 0; i < n; i++) { // Printing value of a[i] in map cout << mp[a[i]] << " "; // Now updating the factors // of a[i] in the map add_factors(a[i], mp); } } // Driver code int main() { int arr[] = { 8, 1, 28, 4, 2, 6, 7 }; int n = sizeof(arr) / sizeof(arr[0]); // Function call count_divisors(arr, n); return 0; }
Java
// Java program to count of multiples // in an Array before every element import java.util.*; class GFG{ // Function to find all factors of N // and keep their count in map static void add_factors(int n, HashMap<Integer,Integer> mp) { // Traverse from 1 to Math.sqrt(N) // if i divides N, // increment i and N/i in map for (int i = 1; i <= (Math.sqrt(n)); i++) { if (n % i == 0) { if (n / i == i) { if(mp.containsKey(i)) mp.put(i, mp.get(i) + 1); else mp.put(i, 1); } else { if(mp.containsKey(i)) mp.put(i, mp.get(i) + 1); else mp.put(i, 1); if(mp.containsKey(n / i)) mp.put(n / i, mp.get(n / i) + 1); else mp.put(n / i, 1); } } } } // Function to count of multiples // in an Array before every element static void count_divisors(int a[], int n) { // To store factors all of all numbers HashMap<Integer,Integer> mp = new HashMap<Integer,Integer>(); // Traverse for all possible i's for (int i = 0; i < n; i++) { // Printing value of a[i] in map System.out.print(mp.get(a[i]) == null ? 0 + " " : mp.get(a[i]) + " "); // Now updating the factors // of a[i] in the map add_factors(a[i], mp); } } // Driver code public static void main(String[] args) { int arr[] = { 8, 1, 28, 4, 2, 6, 7 }; int n = arr.length; // Function call count_divisors(arr, n); } } // This code is contributed by 29AjayKumar
Python3
# Python 3 program to count of multiples # in an Array before every element from collections import defaultdict import math # Function to find all factors of N # and keep their count in map def add_factors(n, mp): # Traverse from 1 to sqrt(N) # if i divides N, # increment i and N/i in map for i in range(1, int(math.sqrt(n)) + 1,): if (n % i == 0): if (n // i == i): mp[i] += 1 else : mp[i] += 1 mp[n // i] += 1 # Function to count of multiples # in an Array before every element def count_divisors(a, n): # To store factors all of all numbers mp = defaultdict(int) # Traverse for all possible i's for i in range(n) : # Printing value of a[i] in map print(mp[a[i]], end=" ") # Now updating the factors # of a[i] in the map add_factors(a[i], mp) # Driver code if __name__ == "__main__": arr = [ 8, 1, 28, 4, 2, 6, 7 ] n = len(arr) # Function call count_divisors(arr, n) # This code is contributed by chitranayal
C#
// C# program to count of multiples // in an Array before every element using System; using System.Collections.Generic; class GFG{ // Function to find all factors of N // and keep their count in map static void add_factors(int n, Dictionary<int,int> mp) { // Traverse from 1 to Math.Sqrt(N) // if i divides N, // increment i and N/i in map for (int i = 1; i <= (Math.Sqrt(n)); i++) { if (n % i == 0) { if (n / i == i) { if(mp.ContainsKey(i)) mp[i] = mp[i] + 1; else mp.Add(i, 1); } else { if(mp.ContainsKey(i)) mp[i] = mp[i] + 1; else mp.Add(i, 1); if(mp.ContainsKey(n / i)) mp[n / i] = mp[n / i] + 1; else mp.Add(n / i, 1); } } } } // Function to count of multiples // in an Array before every element static void count_divisors(int []a, int n) { // To store factors all of all numbers Dictionary<int,int> mp = new Dictionary<int,int>(); // Traverse for all possible i's for (int i = 0; i < n; i++) { // Printing value of a[i] in map Console.Write(!mp.ContainsKey(a[i]) ? 0 + " " : mp[a[i]] + " "); // Now updating the factors // of a[i] in the map add_factors(a[i], mp); } } // Driver code public static void Main(String[] args) { int []arr = { 8, 1, 28, 4, 2, 6, 7 }; int n = arr.Length; // Function call count_divisors(arr, n); } } // This code is contributed by sapnasingh4991
Javascript
<script> // Javascript program to count of multiples // in an Array before every element // Function to find all factors of N // and keep their count in map function add_factors(n, mp) { // Traverse from 1 to sqrt(N) // if i divides N, // increment i and N/i in map for (var i = 1; i <= parseInt(Math.sqrt(n)); i++) { if (n % i == 0) { if (parseInt(n / i) == i) { if(mp.has(i)) mp.set(i, mp.get(i)+1) else mp.set(i, 1) } else { if(mp.has(i)) mp.set(i, mp.get(i)+1) else mp.set(i, 1) if(mp.has(parseInt(n/i))) mp.set(parseInt(n/i), mp.get(parseInt(n/i))+1) else mp.set(parseInt(n/i), 1) } } } return mp; } // Function to count of multiples // in an Array before every element function count_divisors(a, n) { // To store factors all of all numbers var mp = new Map(); // Traverse for all possible i's for (var i = 0; i < n; i++) { // Printing value of a[i] in map document.write( (mp.has(a[i])?mp.get(a[i]):0) + " "); // Now updating the factors // of a[i] in the map mp = add_factors(a[i], mp); } } // Driver code var arr = [8, 1, 28, 4, 2, 6, 7]; var n = arr.length; // Function call count_divisors(arr, n); // This code is contributed by famously. </script>
0 1 0 2 3 0 1
Complejidad de tiempo: O(N * sqrt(val)), donde N es el tamaño de la array y val es el valor máximo de los elementos presentes en la array.
Espacio auxiliar: O(N), ya que estamos usando espacio extra para map mp.
Publicación traducida automáticamente
Artículo escrito por rahulrawat09 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA