IN JAVA
In this problem, we will implement an nth root finder. Recall that the nth root of x is the number when raised to the power n gives x. In particular, please fill in the method findNthRoot(int number, int n, int precision) within the Main class. 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 still 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.
For this question, our program expects 3 lines, where the first line is n (the degree of root to take), the second line is the actual number, and the third line 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
4
use this format for code
public class Main {
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)
{
}
import java.util.Scanner;
public class Main {
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 x = number*1.0/n;
double error = 1/.00000001;
while (error > .0000001){//it will calculate
for a precision of 6 decimalpoins
x = ((n - 1.0) * x +
number / Math.pow(x, n - 1.0)) / n;
error =
Math.abs(Math.pow(x,n)-number);
}
String str = "%."+precision+"f";
return String.format(str,x);
}
}
Get Answers For Free
Most questions answered within 1 hours.