In: Computer Science
In this problem, we will implement an nth root finder. Recall that the nth root of x, written n√ x, is the number when raised to the power n gives x.
In particular, please fill in the findNthRoot(int number, int n, int precision) method in the class NthRootFinder.
The method should return a string representing the nth root of number, rounded to the nearest precision decimal places. If your answer is exact, you should fill in the answer with decimal places (i.e. with input 41 and precision 5, we should return 41.00000.)
You may not use any library functions for this question. In this question, our program expects 3 lines, where the first line is n (the degree of root to take), the second line is a number, and the third number represents the precision.
The output is a single line containing the answer followed by a newline.
For example, the following input would generate the output 20.000: 2 400 3
Additionally, the following input would generate the output 6.86: 2 47 2
code:
/**
*
* @author VISHAL
*/
class NthRootClass
{
static String findNthRoot(int number, int n,int
precision)
{
// intially guessing a random
number between
// 0 and 9
double xPre = Math.random() %
10;
double eps=1.0;
double p=1.0;
// smaller eps, denotes more
accuracy
for(int i=1; i<=precision;
i++)
{
eps/=10;
p*=10;
}
// initializing difference between
two
// roots by INT_MAX
double delX = 2147483647;
// xK denotes current value of
x
double xK = 0.0;
while (delX > eps)
{
xK = ((n - 1.0)
* xPre +
(double)number /
Math.pow(xPre, n - 1)) / (double)n;
delX =
Math.abs(xK - xPre);
xPre = xK;
}
double scale=Math.pow(10,precision);
xK=Math.round(xK*scale)/scale;
return String.valueOf(xK);
}
public static void main (String[] args)
{
System.out.println("Nth root is
" + findNthRoot(47, 2,2));
}
}