Dada una array arr[] que consiste en N enteros y un entero K , la tarea es encontrar la suma de los elementos de la array posibles recorriendo la array y sumando arr[i] / K , K número de veces al final de la array , si arr[i] es divisible por K . De lo contrario, detenga el recorrido.
Ejemplos:
Entrada: arr[] = {4, 6, 8, 2}, K = 2
Salida: 44
Explicación:
Se realizan las siguientes operaciones:
- Para arr[0](= 4): arr[0](= 4) es divisible por 2, por lo tanto agregue 4/2 = 2, 2 números de veces al final de la array. Ahora, la array se modifica a {4, 6, 8, 2, 2, 2}.
- Para arr[1](= 6): arr[1](= 6) es divisible por 2, por lo tanto agregue 6/2 = 3, 2 veces al final de la array. Ahora, la array se modifica a {4, 6, 8, 2, 2, 2, 3, 3}.
- Para arr[2](= 8): arr[2](= 8) es divisible por 2, por lo tanto agregue 8/2 = 4, 2 veces al final de la array. Ahora, la array se modifica a {4, 6, 8, 2, 2, 2, 3, 3, 4, 4}.
- Para arr[3](= 2): arr[3](= 2) es divisible por 2, por lo tanto agregue 2/2 = 1, 2 veces al final de la array. Ahora, la array se modifica a {4, 6, 8, 2, 2, 2, 3, 3, 4, 4, 1, 1}.
- Para arr[4](= 2): arr[4](= 2) es divisible por 2, por lo tanto agregue 2/2 = 1, 2 veces al final de la array. Ahora, la array se modifica a {4, 6, 8, 2, 2, 2, 3, 3, 4, 4, 1, 1, 1, 1}.
- Para arr[5](= 2): arr[5](= 2) es divisible por 2, por lo tanto agregue 2/2 = 1, 2 veces al final de la array. Ahora, la array se modifica a {4, 6, 8, 2, 2, 2, 3, 3, 4, 4, 1, 1, 1, 1, 1, 1}.
Después de completar los pasos anteriores, la suma de los elementos de la array es = 4 + 6 + 8 + 2 + 2 + 2 + 3 + 3 + 4 + 4 + 1 + 1 + 1 + 1 + 1 + 1 = 44.
Entrada: arr[] = {4, 6, 8, 9}, K = 2
Salida: 45
Enfoque ingenuo: el enfoque más simple para resolver el problema dado es atravesar la array dada y agregar el valor (arr[i]/K) K varias veces al final de la array. Después de completar los pasos anteriores, imprima la suma de los elementos de la array .
A continuación se muestra la implementación del enfoque anterior:
C++
// C++ program for the above approach #include <bits/stdc++.h> using namespace std; // Function to calculate sum of array // elements after adding arr[i] / K // to the end of the array if arr[i] // is divisible by K int sum(int arr[], int N, int K) { // Stores the sum of the array int sum = 0; vector<long long> v; // Traverse the array arr[] for (int i = 0; i < N; i++) { v.push_back(arr[i]); } // Traverse the vector for (int i = 0; i < v.size(); i++) { // If v[i] is divisible by K if (v[i] % K == 0) { long long x = v[i] / K; // Iterate over the range // [0, K] for (int j = 0; j < K; j++) { // Update v v.push_back(x); } } // Otherwise else break; } // Traverse the vector v for (int i = 0; i < v.size(); i++) sum = sum + v[i]; // Return the sum of the updated array return sum; } // Driver Code int main() { int arr[] = { 4, 6, 8, 2 }; int K = 2; int N = sizeof(arr) / sizeof(arr[0]); cout << sum(arr, N, K); return 0; }
Java
// Java program for the above approach import java.io.*; import java.lang.*; import java.util.*; class GFG{ // Function to calculate sum of array // elements after adding arr[i] / K // to the end of the array if arr[i] // is divisible by K static int sum(int arr[], int N, int K) { // Stores the sum of the array int sum = 0; ArrayList<Integer> v = new ArrayList<>(); // Traverse the array arr[] for(int i = 0; i < N; i++) { v.add(arr[i]); } // Traverse the vector for(int i = 0; i < v.size(); i++) { // If v[i] is divisible by K if (v.get(i) % K == 0) { int x = v.get(i) / K; // Iterate over the range // [0, K] for(int j = 0; j < K; j++) { // Update v v.add(x); } } // Otherwise else break; } // Traverse the vector v for(int i = 0; i < v.size(); i++) sum = sum + v.get(i); // Return the sum of the updated array return sum; } // Driver Code public static void main(String[] args) { int arr[] = { 4, 6, 8, 2 }; int K = 2; int N = arr.length; System.out.println(sum(arr, N, K)); } } // This code is contributed by Kingash
Python3
# Python3 program for the above approach # Function to calculate sum of array # elements after adding arr[i] / K # to the end of the array if arr[i] # is divisible by K def summ(arr, N, K): # Stores the sum of the array sum = 4 v = [i for i in arr] # Traverse the vector for i in range(len(v)): # If v[i] is divisible by K if (v[i] % K == 0): x = v[i] // K # Iterate over the range # [0, K] for j in range(K): # Update v v.append(x) # Otherwise else: break # Traverse the vector v for i in range(len(v)): sum = sum + v[i] # Return the sum of the updated array return sum # Driver Code if __name__ == '__main__': arr = [ 4, 6, 8, 2 ] K = 2 N = len(arr) print(summ(arr, N, K)) # This code is contributed by mohit kumar 29
C#
// C# program for the above approach using System; using System.Collections.Generic; class GFG { // Function to calculate sum of array // elements after adding arr[i] / K // to the end of the array if arr[i] // is divisible by K static int sum(int[] arr, int N, int K) { // Stores the sum of the array int sum = 0; List<int> v = new List<int>(); // Traverse the array arr[] for (int i = 0; i < N; i++) { v.Add(arr[i]); } // Traverse the vector for (int i = 0; i < v.Count; i++) { // If v[i] is divisible by K if (v[i] % K == 0) { int x = v[i] / K; // Iterate over the range // [0, K] for (int j = 0; j < K; j++) { // Update v v.Add(x); } } // Otherwise else break; } // Traverse the vector v for (int i = 0; i < v.Count; i++) sum = sum + v[i]; // Return the sum of the updated array return sum; } // Driver Code public static void Main(string[] args) { int[] arr = { 4, 6, 8, 2 }; int K = 2; int N = arr.Length; Console.WriteLine(sum(arr, N, K)); } } // This code is contributed by ukasp.
Javascript
<script> // Javascript program for the above approach // Function to calculate sum of array // elements after adding arr[i] / K // to the end of the array if arr[i] // is divisible by K function sum(arr, N, K) { // Stores the sum of the array var sum = 0; var v = []; // Traverse the array arr[] for (var i = 0; i < N; i++) { v.push(arr[i]); } // Traverse the vector for (var i = 0; i < v.length; i++) { // If v[i] is divisible by K if (v[i] % K == 0) { var x = v[i] / K; // Iterate over the range // [0, K] for (var j = 0; j < K; j++) { // Update v v.push(x); } } // Otherwise else break; } // Traverse the vector v for (var i = 0; i < v.length; i++) sum = sum + v[i]; // Return the sum of the updated array return sum; } // Driver Code var arr = [4, 6, 8, 2]; var K = 2; var N = arr.length; document.write( sum(arr, N, K)); </script>
44
Complejidad temporal: O(N * K * log N)
Espacio auxiliar: O(M), M es el elemento máximo del arreglo .
Enfoque eficiente: el enfoque anterior también se puede optimizar en función de las siguientes observaciones:
- Si arr[i] es divisible por K , entonces sumando arr[i] / K , K veces aumenta la suma en arr[i] .
- Por lo tanto, la idea es empujar el arr[i] / K solo una vez al final del vector.
Siga los pasos a continuación para resolver el problema:
- Inicialice una variable, digamos suma como 0 que almacena la suma de todos los elementos de la array array A[] .
- Inicialice una array, diga A[] y almacene todos los elementos de la array arr[] en A[] .
- Inicialice una variable, digamos marcar como 0 que almacena si el elemento se agregará al final de la array o no.
- Atraviese la array A[] y realice los siguientes pasos:
- Si el indicador de valor es 0 y A[i] es divisible por K , presione A[i] al final de V .
- De lo contrario, actualice el valor de la bandera como 1 .
- Incremente el valor de la suma en V[i % N] .
- Después de completar los pasos anteriores, imprima el valor de la suma como la suma resultante.
A continuación se muestra la implementación del enfoque anterior:
C++
// C++ program for the above approach #include <bits/stdc++.h> using namespace std; // Function to calculate sum of array // elements after adding arr[i] / K // to the end of the array if arr[i] // is divisible by K int sum(int arr[], int N, int K) { // Stores the sum of the array int sum = 0; // Stores the array elements vector<int> v; // Traverse the array for (int i = 0; i < N; i++) { v.push_back(arr[i]); } // Stores if the operation // should be formed or not bool flag = 0; // Traverse the vector V for (int i = 0; i < v.size(); i++) { // If flag is false and if // v[i] is divisible by K if (!flag && v[i] % K == 0) v.push_back(v[i] / K); // Otherwise, set flag as true else { flag = 1; } // Increment the sum by v[i % N] sum = sum + v[i % N]; } // Return the resultant sum return sum; } // Driver Code int main() { int arr[] = { 4, 6, 8, 2 }; int K = 2; int N = sizeof(arr) / sizeof(arr[0]); cout << sum(arr, N, K); return 0; }
Java
// Java program for the above approach import java.io.*; import java.util.*; class GFG { // Function to calculate sum of array // elements after adding arr[i] / K // to the end of the array if arr[i] // is divisible by K static int sum(int arr[], int N, int K) { // Stores the sum of the array int sum = 0; // Stores the array elements ArrayList<Integer> v = new ArrayList<Integer>(); // Traverse the array for (int i = 0; i < N; i++) { v.add(arr[i]); } // Stores if the operation // should be formed or not boolean flag = false; // Traverse the vector V for (int i = 0; i < v.size(); i++) { // If flag is false and if // v[i] is divisible by K if (!flag && v.get(i) % K == 0) v.add(v.get(i) / K); // Otherwise, set flag as true else { flag = true; } // Increment the sum by v[i % N] sum = sum + v.get(i % N); } // Return the resultant sum return sum; } // Driver Code public static void main (String[] args) { int arr[] = { 4, 6, 8, 2 }; int K = 2; int N = arr.length; System.out.println(sum(arr, N, K)); } } // This code is contributed by Dharanendra L V.
Python3
# Python program for the above approach # Function to calculate sum of array # elements after adding arr[i] / K # to the end of the array if arr[i] # is divisible by K def Sum(arr, N, K): # Stores the sum of the array sum = 0 # Stores the array elements v = [] # Traverse the array for i in range(N): v.append(arr[i]) # Stores if the operation # should be formed or not flag = False i = 0 lenn = len(v) # Traverse the vector V while(i < lenn): # If flag is false and if # v[i] is divisible by K if( flag == False and (v[i] % K == 0)): v.append(v[i]//K) # Otherwise, set flag as true else: flag = True # Increment the sum by v[i % N] sum += v[i % N] i += 1 lenn = len(v) # Return the resultant sum return sum # Driver Code arr = [ 4, 6, 8, 2] K = 2 N = len(arr) print(Sum(arr, N, K)) # This code is contributed by avanitrachhadiya2155
C#
// C# program for the above approach using System; using System.Collections.Generic; class GFG{ // Function to calculate sum of array // elements after adding arr[i] / K // to the end of the array if arr[i] // is divisible by K static int sum(int []arr, int N, int K) { // Stores the sum of the array int sum = 0; // Stores the array elements List<int> v = new List<int>(); // Traverse the array for(int i = 0; i < N; i++) { v.Add(arr[i]); } // Stores if the operation // should be formed or not bool flag = false; // Traverse the vector V for(int i = 0; i < v.Count; i++) { // If flag is false and if // v[i] is divisible by K if (!flag && v[i] % K == 0) v.Add(v[i] / K); // Otherwise, set flag as true else { flag = true; } // Increment the sum by v[i % N] sum = sum + v[i % N]; } // Return the resultant sum return sum; } // Driver Code static void Main() { int[] arr = { 4, 6, 8, 2 }; int K = 2; int N = arr.Length; Console.WriteLine(sum(arr, N, K)); } } // This code is contributed by SoumikMondal
Javascript
<script> // javascript program for the above approach // Function to calculate sum of array // elements after adding arr[i] / K // to the end of the array if arr[i] // is divisible by K function sum(arr, N, K) { // Stores the sum of the array var sum = 0; var i; // Stores the array elements var v = []; // Traverse the array for (i = 0; i < N; i++) { v.push(arr[i]); } // Stores if the operation // should be formed or not var flag = 0; // Traverse the vector V for (i = 0; i < v.length; i++) { // If flag is false and if // v[i] is divisible by K if (!flag && v[i] % K == 0) v.push(v[i] / K); // Otherwise, set flag as true else { flag = 1; } // Increment the sum by v[i % N] sum = sum + v[i % N]; } // Return the resultant sum return sum; } // Driver Code var arr = [4, 6, 8, 2]; var K = 2; var N = arr.length; document.write(sum(arr, N, K)); </script>
44
Complejidad de Tiempo: O(N * log N)
Espacio Auxiliar: O(N * log N)
Publicación traducida automáticamente
Artículo escrito por IshwarGupta y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA