In: Computer Science
Need to able to solve this method WITHOUT using ANY java libraries.
------------------------------
import java.util.Scanner;
public class nthroot {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Read n (for taking the nth root)
int num = 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, num, precision));
}
private static String findnthRoot(int number, int num, int
precision) {
//code here
}
}
CODE
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 num = Integer.parseInt(sc.nextLine());
// Read number to take the nth root of
int number = Integer.parseInt(sc.nextLine());
// Read the desired precision
double precision = Double.parseDouble(sc.nextLine());
// Print the answer
System.out.println(findnthRoot(number, num, precision));
}
private static String findnthRoot(int number, int num, double precision) {
double guess = 1;
double delX = 2147483647;
Double currentX = 0.0;
// loop untill we reach desired accuracy
while (delX > precision)
{
// calculating current value from previous
// value by newton's method
currentX = ((num - 1.0) * guess +
(double)number / Math.pow(guess, num - 1)) / (double)num;
delX = (currentX - guess) < 0 ? -1 * (currentX - guess) : (currentX - guess);
guess = currentX;
}
return String.valueOf(currentX);
}
}