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