# Java Program to Implement Nth Root Algorithm

«
»
This is a Java Program to Implement Nth Root Algorithm. This program is used to calculate n th root of a number x.

Here is the source code of the Java Program to Implement Nth Root Algorithm. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

1. `/**`
2. ` ** Java Program to implement Nth Root Algorithm`
3. ` **/`
4. ` `
5. `import java.util.Scanner;`
6. ` `
7. `/** Class NthRoot **/`
8. `public class NthRoot`
9. `{`
10. `    public double nthroot(int n, double x) `
11. `    {`
12. `        return nthroot(n, x, .0001);`
13. `    }`
14. `    public double nthroot(int n, double x, double p) `
15. `    {`
16. `        if(x < 0) `
17. `        {`
18. `            System.err.println("Negative!");`
19. `            return -1;`
20. `        }`
21. `        if(x == 0) `
22. `            return 0;`
23. `        double x1 = x;`
24. `        double x2 = x / n;  `
25. `        while (Math.abs(x1 - x2) > p) `
26. `        {`
27. `            x1 = x2;`
28. `            x2 = ((n - 1.0) * x2 + x / Math.pow(x2, n - 1.0)) / n;`
29. `        }`
30. `        return x2;`
31. `    }`
32. `    /** Main **/`
33. `    public static void main(String[] args)`
34. `    {`
35. `        Scanner scan = new Scanner(System.in);`
36. `        System.out.println("Nth Root Algorithm Test\n");`
37. `        System.out.println("Enter n and x");`
38. `        int n = scan.nextInt();`
39. `        double x = scan.nextInt();`
40. `        NthRoot nr = new NthRoot();`
41. `        double root = nr.nthroot(n, x);`
42. `        System.out.println("\nRoot = "+ root);`
43. `    }    `
44. `}`

```Nth Root Algorithm Test

Enter n and x
2
3

Root = 1.7320508100147274```

Sanfoundry Global Education & Learning Series – 1000 Java Programs. 