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.
/**
 ** Java Program to implement Nth Root Algorithm
 **/
 
import java.util.Scanner;
 
/** Class NthRoot **/
public class NthRoot
{
    public double nthroot(int n, double x) 
    {
        return nthroot(n, x, .0001);
    }
    public double nthroot(int n, double x, double p) 
    {
        if(x < 0) 
        {
            System.err.println("Negative!");
            return -1;
        }
        if(x == 0) 
            return 0;
        double x1 = x;
        double x2 = x / n;  
        while (Math.abs(x1 - x2) > p) 
        {
            x1 = x2;
            x2 = ((n - 1.0) * x2 + x / Math.pow(x2, n - 1.0)) / n;
        }
        return x2;
    }
    /** Main **/
    public static void main(String[] args)
    {
        Scanner scan = new Scanner(System.in);
        System.out.println("Nth Root Algorithm Test\n");
        System.out.println("Enter n and x");
        int n = scan.nextInt();
        double x = scan.nextInt();
        NthRoot nr = new NthRoot();
        double root = nr.nthroot(n, x);
        System.out.println("\nRoot = "+ root);
    }    
}
Output:
Nth Root Algorithm Test Enter n and x 2 3 Root = 1.7320508100147274
Related posts:
Java Program to Implement the Binary Counting Method to Generate Subsets of a Set
Guava Collections Cookbook
The XOR Operator in Java
Reading an HTTP Response Body as a String in Java
Java – String to Reader
A Custom Media Type for a Spring REST API
Finding the Differences Between Two Lists in Java
Spring Boot - Securing Web Applications
Functional Interfaces in Java 8
Apache Commons Collections MapUtils
Adding Parameters to HttpClient Requests
Spring Boot - Admin Server
Java Program to Implement Park-Miller Random Number Generation Algorithm
Spring Cloud Series – The Gateway Pattern
Retrieve User Information in Spring Security
Using Custom Banners in Spring Boot
Hướng dẫn sử dụng Printing Service trong Java
Sending Emails with Java
A Quick Guide to Using Keycloak with Spring Boot
Java Program to Implement Shell Sort
Using the Not Operator in If Conditions in Java
Java Program to Implement Ternary Heap
Java 14 Record Keyword
Các chương trình minh họa sử dụng Cấu trúc điều khiển trong Java
ArrayList trong java
Introduction to Thread Pools in Java
Spring REST API + OAuth2 + Angular
Spring Security OAuth2 – Simple Token Revocation
Java Program to Implement Variable length array
HTTP Authentification and CGI/Servlet
Java Program to Implement the Hungarian Algorithm for Bipartite Matching
Checked and Unchecked Exceptions in Java