Dado un arreglo ‘arr’ de enteros positivos, la tarea es contar el número de números compuestos en el arreglo.
Nota: 1 no es ni primo ni compuesto .
Ejemplos:
Entrada: arr[] = {1, 3, 4, 5, 7}
Salida: 1
4 es el único número compuesto.
Entrada: arr[] = {1, 2, 3, 4, 5, 6, 7}
Salida: 2
Enfoque ingenuo: una solución simple es atravesar la array y hacer una prueba de primalidad en cada elemento.
Enfoque eficiente: el uso de la criba de Eratóstenes genera un vector booleano hasta el tamaño del elemento máximo de la array que se puede usar para verificar si un número es primo o no. También agregue 0 y 1 como números primos para que no se cuenten como números compuestos. Ahora recorra la array y encuentre el recuento de los elementos que están compuestos utilizando el vector booleano generado.
A continuación se muestra la implementación del enfoque anterior:
C++
// C++ program to count the // number of composite numbers // in the given array #include <bits/stdc++.h> using namespace std; // Function that returns the // the count of composite numbers int compositeCount(int arr[], int n, int* sum) { // Find maximum value in the array int max_val = *max_element(arr, arr + n); // Use sieve to find all prime numbers // less than or equal to max_val // Create a boolean array "prime[0..n]". A // value in prime[i] will finally be false // if i is Not a prime, else true. vector<bool> prime(max_val + 1, true); // Set 0 and 1 as primes as // they don't need to be // counted as composite numbers prime[0] = true; prime[1] = true; for (int p = 2; p * p <= max_val; p++) { // If prime[p] is not changed, then // it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= max_val; i += p) prime[i] = false; } } // Count all composite // numbers in the arr[] int count = 0; for (int i = 0; i < n; i++) if (!prime[arr[i]]) { count++; *sum = *sum + arr[i]; } return count; } // Driver code int main() { int arr[] = { 1, 2, 3, 4, 5, 6, 7 }; int n = sizeof(arr) / sizeof(arr[0]); int sum = 0; cout << "Count of Composite Numbers = " << compositeCount(arr, n, &sum); cout << "\nSum of Composite Numbers = " << sum; return 0; }
Java
import java.util.*; // Java program to count the // number of composite numbers // in the given array class GFG { static int sum = 0; // Function that returns the // the count of composite numbers static int compositeCount(int arr[], int n) { // Find maximum value in the array int max_val = Arrays.stream(arr).max().getAsInt(); // Use sieve to find all prime numbers // less than or equal to max_val // Create a boolean array "prime[0..n]". A // value in prime[i] will finally be false // if i is Not a prime, else true. Vector<Boolean> prime = new Vector<Boolean>(max_val + 1); for (int i = 0; i < max_val + 1; i++) { prime.add(i, Boolean.TRUE); } // Set 0 and 1 as primes as // they don't need to be // counted as composite numbers prime.add(0, Boolean.TRUE); prime.add(1, Boolean.TRUE); for (int p = 2; p * p <= max_val; p++) { // If prime[p] is not changed, then // it is a prime if (prime.get(p) == true) { // Update all multiples of p for (int i = p * 2; i <= max_val; i += p) { prime.add(i, Boolean.FALSE); } } } // Count all composite // numbers in the arr[] int count = 0; for (int i = 0; i < n; i++) { if (!prime.get(arr[i])) { count++; sum = sum + arr[i]; } } return count; } // Driver code public static void main(String[] args) { int arr[] = {1, 2, 3, 4, 5, 6, 7}; int n = arr.length; System.out.print("Count of Composite Numbers = " + compositeCount(arr, n)); System.out.print("\nSum of Composite Numbers = " + sum); } } // This code has been contributed by 29AjayKumar
Python3
# Python3 program to count the # number of composite numbers # in the given array # Function that returns the # the count of composite numbers def compositeCount(arr, n): Sum = 0 # Find maximum value in the array max_val = max(arr) # Use sieve to find all prime numbers # less than or equal to max_val # Create a boolean array "prime[0..n]". # A value in prime[i] will finally be # false if i is Not a prime, else True. prime = [True for i in range(max_val + 1)] # Set 0 and 1 as primes as # they don't need to be # counted as composite numbers prime[0] = True prime[1] = True for p in range(2, max_val + 1): if p * p > max_val: break # If prime[p] is not changed, # then it is a prime if (prime[p] == True): # Update all multiples of p for i in range(p * 2, max_val + 1, p): prime[i] = False # Count all composite numbers # in the arr[] count = 0 for i in range(n): if (prime[arr[i]] == False): count += 1 Sum = Sum + arr[i] return count, Sum # Driver code arr = [1, 2, 3, 4, 5, 6, 7 ] n = len(arr) count, Sum = compositeCount(arr, n) print("Count of Composite Numbers = ", count) print("Sum of Composite Numbers = ", Sum) // This code is contributed by Mohit Kumar
C#
// C# program to count the // number of composite numbers // in the given array using System; using System.Linq; using System.Collections; class GFG { static int sum1=0; // Function that returns the // the count of composite numbers static int compositeCount(int []arr, int n, int sum) { // Find maximum value in the array int max_val = arr.Max(); // Use sieve to find all prime numbers // less than or equal to max_val // Create a boolean array "prime[0..n]". A // value in prime[i] will finally be false // if i is Not a prime, else true. bool[] prime=new bool[max_val + 1]; // Set 0 and 1 as primes as // they don't need to be // counted as composite numbers prime[0] = false; prime[1] = false; for (int p = 2; p * p <= max_val; p++) { // If prime[p] is not changed, then // it is a prime if (prime[p] == false) { // Update all multiples of p for (int i = p * 2; i <= max_val; i += p) prime[i] = true; } } // Count all composite // numbers in the arr[] int count = 0; for (int i = 0; i < n; i++) if (prime[arr[i]]) { count++; sum = sum + arr[i]; } sum1 = sum; return count; } // Driver code static void Main() { int []arr = { 1, 2, 3, 4, 5, 6, 7 }; int n = arr.Length; int sum = 0; Console.Write("Count of Composite Numbers = "+ compositeCount(arr, n, sum)); Console.Write("\nSum of Composite Numbers = "+sum1); } } // This code is contributed by mits
PHP
<?php // PHP program to count the // number of composite numbers // in the given array // Function that returns the // the count of composite numbers function compositeCount($arr, $n, &$sum) { // Find maximum value in the array $max_val = max($arr); // Use sieve to find all prime numbers // less than or equal to max_val // Create a boolean array "prime[0..n]". A // value in prime[i] will finally be false // if i is Not a prime, else true. $prime=array_fill(0,$max_val + 1, true); // Set 0 and 1 as primes as // they don't need to be // counted as composite numbers $prime[0] = true; $prime[1] = true; for ($p = 2; $p * $p <= $max_val; $p++) { // If prime[p] is not changed, then // it is a prime if ($prime[$p] == true) { // Update all multiples of p for ($i = $p * 2; $i <= $max_val; $i += $p) $prime[$i] = false; } } // Count all composite // numbers in the arr[] $count = 0; for ($i = 0; $i < $n; $i++) if (!$prime[$arr[$i]]) { $count++; $sum = $sum + $arr[$i]; } return $count; } // Driver code $arr = array( 1, 2, 3, 4, 5, 6, 7 ); $n = count($arr); $sum = 0; echo "Count of Composite Numbers = ".compositeCount($arr, $n, $sum); echo "\nSum of Composite Numbers = ".$sum; // This code is contributed by mits ?>
Javascript
<script> // Javascript program to count the // number of composite numbers // in the given array // Function that returns the // the count of composite numbers let sum = 0; function compositeCount(arr, n) { // Find maximum value in the array let max_val = arr.sort((a, b) => b - a)[0]; // Use sieve to find all prime numbers // less than or equal to max_val // Create a boolean array "prime[0..n]". A // value in prime[i] will finally be false // if i is Not a prime, else true. let prime = new Array(max_val + 1).fill(true); // Set 0 and 1 as primes as // they don't need to be // counted as composite numbers prime[0] = true; prime[1] = true; for (let p = 2; p * p <= max_val; p++) { // If prime[p] is not changed, then // it is a prime if (prime[p] == true) { // Update all multiples of p for (let i = p * 2; i <= max_val; i += p) prime[i] = false; } } // Count all composite // numbers in the arr[] let count = 0; for (let i = 0; i < n; i++) if (!prime[arr[i]]) { count++; sum = sum + arr[i]; } return count; } // Driver code let arr = new Array(1, 2, 3, 4, 5, 6, 7); let n = arr.length; document.write("Count of Composite Numbers = " + compositeCount(arr, n, sum)); document.write("<br>Sum of Composite Numbers = " + sum); // This code is contributed by gfgking </script>
Count of Composite Numbers = 2 Sum of Composite Numbers = 10
Complejidad del tiempo: O(nlog(logn))
Complejidad del espacio : O(n) ya que se está utilizando el espacio auxiliar
Publicación traducida automáticamente
Artículo escrito por VishalBachchas y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA