Dada una array de enteros. La tarea es calcular la cuenta de un número de elementos que son divisibles por un número k dado.
Ejemplos:
Input: arr[] = { 2, 6, 7, 12, 14, 18 }, k = 3 Output: 3 Numbers which are divisible by k are { 6, 12, 18 } Input: arr[] = { 2, 6, 7, 12, 14, 18 }, k = 2 Output: 5
Método 1: comience a recorrer la array y verifique si el elemento actual es divisible por K. En caso afirmativo, incremente el conteo. Imprime el conteo cuando se recorren todos los elementos.
A continuación se muestra la implementación del enfoque anterior:
C++
// C++ program to Count the number of elements // in an array which are divisible by k #include <iostream> using namespace std; // Function to count the elements int CountTheElements(int arr[], int n, int k) { int counter = 0; for (int i = 0; i < n; i++) { if (arr[i] % k == 0) counter++; } return counter; } // Driver code int main() { int arr[] = { 2, 6, 7, 12, 14, 18 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 3; cout << CountTheElements(arr, n, k); return 0; }
Java
// Java program to Count the number of elements // in an array which are divisible by k import java.util.*; class Geeks { // Function to count the elements static int CountTheElements(int arr[], int n, int k) { int counter = 0; for (int i = 0; i < n; i++) { if (arr[i] % k == 0) counter++; } return counter; } // Driver code public static void main(String args[]) { int arr[] = { 2, 6, 7, 12, 14, 18 }; int n = arr.length; int k = 3; System.out.println(CountTheElements(arr, n, k)); } } // This code is contributed by ankita_saini
Python3
# Python 3 program to Count the # number of elements in an array # which are divisible by k # Function to count the elements def CountTheElements(arr, n, k): counter = 0 for i in range(0, n, 1): if (arr[i] % k == 0): counter = counter+1 return counter # Driver code if __name__ == '__main__': arr = [2, 6, 7, 12, 14, 18]; n = len(arr) k = 3 print(CountTheElements(arr, n, k)) # This code is contributed by # Surendra_Gangwar
C#
// C# program to Count the number of elements // in an array which are divisible by k using System; class Geeks { // Function to count the elements static int CountTheElements(int []arr, int n, int k) { int counter = 0; for (int i = 0; i < n; i++) { if (arr[i] % k == 0) counter++; } return counter; } // Driver code public static void Main() { int []arr = { 2, 6, 7, 12, 14, 18 }; int n = arr.Length; int k = 3; Console.WriteLine(CountTheElements(arr, n, k)); } } //This code is contributed by inder_verma..
PHP
<?php // PHP program to Count the number of elements // in an array which are divisible by k // Function to count the elements function CountTheElements($arr, $n, $k) { $counter = 0; for ($i = 0; $i < $n; $i++) { if ($arr[$i] % $k == 0) $counter++; } return $counter; } // Driver code $arr = array( 2, 6, 7, 12, 14, 18 ); $n = count($arr); $k = 3; echo CountTheElements($arr, $n, $k); // This code is contributed by inder_verma ?>
Javascript
<script> // Javascript program to Count the number // of elements in an array which are // divisible by k // Function to count the elements function CountTheElements(arr, n, k) { let counter = 0; for(let i = 0; i < n; i++) { if (arr[i] % k == 0) counter++; } return counter; } // Driver code let arr = [ 2, 6, 7, 12, 14, 18 ]; let n = arr.length; let k = 3; document.write(CountTheElements(arr, n, k)); // This code is contributed by subhammahato348 </script>
3
Complejidad temporal: O(n)
Espacio auxiliar: O(1)
Método 2: otra forma de hacerlo es usar la función incorporada: Count_if . Esta función toma punteros al principio y al final del contenedor que contiene los elementos y la función auxiliar. Devolverá el recuento de elementos para los que la función devolverá verdadero.
A continuación se muestra la implementación del enfoque anterior:
C++
// C++ implementation of the above approach #include <bits/stdc++.h> using namespace std; int main() { vector<int> v{ 2, 6, 7, 12, 14, 18 }; // Count the number elements which when passed // through the function (3rd argument) returns true int res = count_if(v.begin(), v.end(), [](int i, int k = 3) { return i % k == 0; }); cout << res; return 0; }
Java
// Java implementation of the above approach import java.util.*; class GFG { public static void main(String[] args) { int []v = { 2, 6, 7, 12, 14, 18 }; // Count the number elements which when passed // through the function (3rd argument) returns true int res = 0; for(int i = 0; i < v.length; i++) { if(v[i] % 3 == 0) res++; } System.out.print(res); } } // This code is contributed by gauravrajput1
Python3
# Java implementation of the above approach v = [ 2, 6, 7, 12, 14, 18 ]; # Count the number elements which when passed # through the function (3rd argument) returns true res = 0 for i in range(0,len(v)): if(v[i] % 3 == 0): res+=1 print(res) # This code is contributed by shivanisinghss2110
C#
// C# implementation of the above approach using System; class GFG { public static void Main(String[] args) { int []v = { 2, 6, 7, 12, 14, 18 }; // Count the number elements which when passed // through the function (3rd argument) returns true int res = 0; for(int i = 0; i < v.Length; i++) { if(v[i] % 3 == 0) res++; } Console.Write(res); } } // This code is contributed by shivanisinghss2110
Javascript
<script> // JavaScript implementation of the above approach var v = [ 2, 6, 7, 12, 14, 18 ]; // Count the number elements which when passed // through the function (3rd argument) returns true var res = 0; for(var i = 0; i < v.length; i++) { if(v[i] % 3 == 0) res++; } document.write(res); // This code is contributed by shivanisinghss2110 </script>
3
Complejidad temporal: O(N)
Espacio auxiliar: O(1)
Sugiera si alguien tiene una mejor solución que sea más eficiente en términos de espacio y tiempo.
Este artículo es una contribución de Aarti_Rathi . 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 imdhruvgupta y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA