Calcule la potencia raíz media Kth de todos los elementos de la array

Dada una array arr[] y un entero K , la tarea es calcular la K -ésima raíz de la media aritmética de las K -ésimas potencias de todos los elementos de la array.

Ejemplos:

Entrada: arr[] = {1, 2, 3, 4, 5}, K = 2
Salida: 3,31662
Explicación:
Suma de todas las késimas potencias de los elementos del arreglo = 1 + 4 + 9 + 16 + 25 = 55
El valor de raíz media K -ésima potencia de los elementos del arreglo = √(55 / 5) = √11 = 3.31662

Entrada: arr[] = {10, 4, 6, 8}, K = 3
Salida: 7.34847

Enfoque: La raíz media de las K -ésimas potencias de los elementos del arreglo viene dada por la ecuación: 

\sqrt[k]{\frac{arr_{1}^{k} + arr_{2}^{k} + arr_{2}^{k} + ..... arr_{n}^{k}}{n}}

Por lo tanto, la idea es calcular la K -ésima potencia de cada elemento del arreglo. Luego, encuentra la media aritmética de esos elementos. Finalmente, calcule la raíz K -ésima de la media calculada.

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 find the Nth root
double nthRoot(int A, int N)
{
    // Initially guessing random
    // numberbetween 0 and 9
    double xPre = rand() % 10;
 
    // Smaller eps for more accuracy
    double eps = 1e-3;
 
    // Initialize difference between
    // the two roots by INT_MAX
    double delX = INT_MAX;
 
    // xK denotes current value of x
    double xK;
 
    // Iterate until desired
    // accuracy is reached
    while (delX > eps) {
 
        // Find the current value
        // from previous value by
        // newton's method
        xK = ((N - 1.0) * xPre
              + (double)A / pow(xPre, N - 1))
             / (double)N;
 
        delX = abs(xK - xPre);
        xPre = xK;
    }
 
    return xK;
}
 
// Function to calculate the Root
// Mean kth power of array elements
float RMNValue(int arr[], int n, int k)
{
    int Nth = 0;
 
    float mean = 0.0, root = 0.0;
 
    // Calculate sum of kth power
    for (int i = 0; i < n; i++) {
        Nth += pow(arr[i], k);
    }
 
    // Calculate Mean
    mean = (Nth / (float)(n));
 
    // Calculate kth Root of mean
    root = nthRoot(mean, k);
 
    return root;
}
 
// Driver Code
int main()
{
    int arr[] = { 10, 4, 6, 8 };
    int N = sizeof(arr) / sizeof(arr[0]);
    int K = 3;
 
    // Function Call
    cout << RMNValue(arr, N, K);
 
    return 0;
}

Java

// Java program for
// the above approach
class GFG{
 
// Function to find the
  // Nth root
static double nthRoot(int A,
                      int N)
{
  // Initially guessing random
  // numberbetween 0 and 9
  double xPre = (Math.random() * 10) % 10;
 
  // Smaller eps for more accuracy
  double eps = 1e-3;
 
  // Initialize difference between
  // the two roots by Integer.MAX_VALUE
  double delX = Integer.MAX_VALUE;
 
  // xK denotes current value of x
  double xK = 0;
 
  // Iterate until desired
  // accuracy is reached
  while (delX > eps)
  {
    // Find the current value
    // from previous value by
    // newton's method
    xK = ((N - 1.0) * xPre +
          (double)A /
          Math.pow(xPre, N - 1)) /
          (double)N;
 
    delX = Math.abs(xK - xPre);
    xPre = xK;
  }
 
  return xK;
}
 
// Function to calculate the Root
// Mean kth power of array elements
static float RMNValue(int arr[],
                      int n, int k)
{
  int Nth = 0;
  float mean = 0, root = 0;
 
  // Calculate sum of kth power
  for (int i = 0; i < n; i++)
  {
    Nth += Math.pow(arr[i], k);
  }
 
  // Calculate Mean
  mean = (Nth / (float)(n));
 
  // Calculate kth Root of mean
  root = (float) nthRoot((int)mean, k);
 
  return root;
}
 
// Driver Code
public static void main(String[] args)
{
  int arr[] = {10, 4, 6, 8};
  int N = arr.length;
  int K = 3;
 
  // Function Call
  System.out.print(RMNValue(arr, N, K));
 
}
}
 
// This code is contributed by Rajput-Ji

Python3

# Python3 program for
# the above approach
import sys
import random
 
# Function to find
# the Nth root
def nthRoot(A, N):
 
    # Initially guessing random
    # numberbetween 0 and 9
    xPre = random.random() % 10
 
    # Smaller eps for
    # more accuracy
    eps = 1e-3
 
    # Initialize difference between
    # the two roots by INT_MAX
    delX = sys.maxsize
 
    # xK denotes current
    # value of x
    xK = 0
 
    # Iterate until desired
    # accuracy is reached
    while (delX > eps):
 
        # Find the current value
        # from previous value by
        # newton's method
        xK = (((N - 1.0) * xPre +
                A / pow(xPre, N - 1)) / N)
        delX = abs(xK - xPre)
        xPre = xK
    
    return xK
 
# Function to calculate the Root
# Mean kth power of array elements
def RMNValue(arr, n, k):
 
    Nth = 0
    mean = 0.0
    root = 0.0
 
    # Calculate sum of kth power
    for i in range (n):
        Nth += pow(arr[i], k)
 
    # Calculate Mean
    mean = (Nth // (n))
 
    # Calculate kth Root of mean
    root = nthRoot(mean, k)
 
    return root
 
# Driver Code
if __name__ == "__main__":
 
    arr = [10, 4, 6, 8 ]
    N = len(arr)
    K = 3
 
    # Function Call
    print ( RMNValue(arr, N, K))
 
# This code is contributed by Chitranayal

C#

// C# program for the above approach 
using System;
 
class GFG{
  
// Function to find the
// Nth root
static double nthRoot(int A, int N)
{
     
    // Instantiate random number generator
    Random rand = new Random();
         
    // Initially guessing random
    // numberbetween 0 and 9
    double xPre = (rand.Next() * 10) % 10;
     
    // Smaller eps for more accuracy
    double eps = 1e-3;
     
    // Initialize difference between
    // the two roots by Integer.MAX_VALUE
    double delX = Int32.MaxValue;
     
    // xK denotes current value of x
    double xK = 0;
     
    // Iterate until desired
    // accuracy is reached
    while (delX > eps)
    {
         
        // Find the current value
        // from previous value by
        // newton's method
        xK = ((N - 1.0) * xPre +
              (double)A /
              Math.Pow(xPre, N - 1)) /
              (double)N;
         
        delX = Math.Abs(xK - xPre);
        xPre = xK;
    }
    return xK;
}
  
// Function to calculate the Root
// Mean kth power of array elements
static float RMNValue(int[] arr, int n,
                                 int k)
{
    int Nth = 0;
    float mean = 0, root = 0;
     
    // Calculate sum of kth power
    for(int i = 0; i < n; i++)
    {
        Nth += (int)Math.Pow(arr[i], k);
    }
     
    // Calculate Mean
    mean = (Nth / (float)(n));
     
    // Calculate kth Root of mean
    root = (float)nthRoot((int)mean, k);
     
    return root;
}
  
// Driver Code
public static void Main()
{
    int[] arr = { 10, 4, 6, 8 };
    int N = arr.Length;
    int K = 3;
     
    // Function call
    Console.Write(RMNValue(arr, N, K));
}
}
 
// This code is contributed by code_hunt

Javascript

<script>
 
// Javascript program for the above approach 
 
// Function to find the
// Nth root
function nthRoot(A, N)
{
     
    // Initially guessing random
    // numberbetween 0 and 9
    var xPre = (Math.random() * 10) % 10;
     
    // Smaller eps for more accuracy
    var eps = 1e-3;
     
    // Initialize difference between
    // the two roots by Integer.MAX_VALUE
    var delX = Number.MAX_VALUE;
     
    // xK denotes current value of x
    var xK = 0;
     
    // Iterate until desired
    // accuracy is reached
    while (delX > eps)
    {
         
        // Find the current value
        // from previous value by
        // newton's method
        xK = ((N - 1.0) * xPre + A /
              Math.pow(xPre, N - 1)) / N;
         
        delX = Math.abs(xK - xPre);
        xPre = xK;
    }
    return xK;
}
 
// Function to calculate the Root
// Mean kth power of array elements
function RMNValue(arr, n, k)
{
    var Nth = 0;
    var mean = 0, root = 0;
     
    // Calculate sum of kth power
    for(var i = 0; i < n; i++)
    {
        Nth += Math.pow(arr[i], k);
    }
     
    // Calculate Mean
    mean = (Nth / (n));
     
    // Calculate kth Root of mean
    root = nthRoot(mean, k);
     
    return root;
}
 
// Driver Code
var arr = [ 10, 4, 6, 8 ];
var N = arr.length;
var K = 3;
 
// Function Call
document.write(RMNValue(arr, N, K));
 
// This code is contributed by Ankita saini
 
</script>
Producción: 

7.65172

 

Complejidad de tiempo: O(N*log(suma)), donde la suma es la suma del cuadrado de todos los números dados en la array. 
Espacio Auxiliar: O(1)

Publicación traducida automáticamente

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