Hello !!
Make an algorithm that calculates the nth root of a number in C language.
Example :
Thank you !
Answers
Answer:
Following code also gives a good approximation:
- #include<stdio.h>
- #include<math.h>
- int main(){
- double b=0.0;
- double a=0.001;
- double r=0;
- printf("Type the number and root value (e.g.2 for square root)\n");
- scanf("%lf %lf",&b,&r);
thank you for your opportunity
Explanation:
PLEASE MARK MY ANSWER AS A BRAINLIEST ANSWER...PLEASE...I AM IN NEED OF THAT
PLEASE FOLLOW ME
Answer:
Hey mate here is your answer...
according to newton’s method
x(K+1) = x(K) – f(x) / f’(x)
here f(x) = x^(N) – A
so f’(x) = N*x^(N - 1)
and x(K) denoted the value of x at Kth iteration
putting the values and simplifying we get,
x(K + 1) = (1 / N) * ((N - 1) * x(K) + A / x(K) ^ (N - 1))
Using above relation, we can solve the given problem. In below code we iterate over values of x, until difference between two consecutive values of x become lower than desired accuracy.
Below is the implementation of above approach:
C++
// C++ program to calculate Nth root of a number
#include <bits/stdc++.h>
using namespace std;
// method returns Nth power of A
double nthRoot(int A, int N)
{
// intially guessing a random number between
// 0 and 9
double xPre = rand() % 10;
// smaller eps, denotes more accuracy
double eps = 1e-3;
// initializing difference between two
// roots by INT_MAX
double delX = INT_MAX;
// xK denotes current value of x
double xK;
// loop untill we reach desired accuracy
while (delX > eps)
{
// calculating 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;
}
// Driver code to test above methods
int main()
{
int N = 4;
int A = 81;
double nthRootValue = nthRoot(A, N);
cout << "Nth root is " << nthRootValue << endl;
hope it's helpful for you