In: Computer Science
PLEASE DO NOT CHANGE THE CODE BELOW!
In this problem, we will implement an nth root finder. 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
import java.util.Scanner;
public class NthRootFinder {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Read n (for taking the nth root)
int n = Integer.parseInt(sc.nextLine());
// Read number to take the nth root of
int number = Integer.parseInt(sc.nextLine());
// Read the desired precision
int precision = Integer.parseInt(sc.nextLine());
// Print the answer
System.out.println(findNthRoot(number, n, precision));
}
private static String findNthRoot(int number, int n, int precision)
{
// TODO complete this method
double
return 0;
}
}
import java.util.Scanner; public class NthRootFinder { public static double myPow(double x, double n) { if(n == 0) { return 1; } if(n > 0) { return x * myPow(x, n-1); } else { return myPow(x, n + 1) * 1.0/x; } } public static void main(String[] args) { Scanner sc = new Scanner(System.in); // Read n (for taking the nth root) int n = Integer.parseInt(sc.nextLine()); // Read number to take the nth root of int number = Integer.parseInt(sc.nextLine()); // Read the desired precision int precision = Integer.parseInt(sc.nextLine()); // Print the answer System.out.println(findNthRoot(number, n, precision)); } private static String findNthRoot(int number, int n, int precision) { double xPrevious = (double)number/n; // just to start with a value double delX = Double.MAX_VALUE; // for difference in actual and assumed value // xK denotes current value of x double xCurrent = xPrevious; // loop untill we reach desired accuracy while (delX > myPow(10, -precision)) { // calculating root approximation newton's method xCurrent = ((n - 1.0) * xPrevious + (double)number/myPow(xPrevious, n-1)) / (double)n; delX = xCurrent - xPrevious; if(delX < 0) { delX *= -1; } xPrevious = xCurrent; } return String.format("%." + precision + "f", xPrevious); } }