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 IdentityHashMap API
The SpringJUnitConfig and SpringJUnitWebConfig Annotations in Spring 5
Introduction to Eclipse Collections
Convert XML to JSON Using Jackson
Java Program to Find the Number of Ways to Write a Number as the Sum of Numbers Smaller than Itself
Câu lệnh điều khiển vòng lặp trong Java (break, continue)
Java Program to Find Minimum Number of Edges to Cut to make the Graph Disconnected
Java – Convert File to InputStream
Spring Cloud AWS – RDS
Multi Dimensional ArrayList in Java
Spring – Injecting Collections
Overflow and Underflow in Java
Java Program to Implement HashMap API
Spring Boot - Cloud Configuration Client
Java Program to Implement LinkedHashMap API
Find the Registered Spring Security Filters
Handling Errors in Spring WebFlux
Guava CharMatcher
Guide to Spring Cloud Kubernetes
Bootstrapping Hibernate 5 with Spring
Spring Boot - Bootstrapping
Java Program to Implement Hash Tree
Returning Image/Media Data with Spring MVC
Java Program to Implement Dijkstra’s Algorithm using Set
Java Program to Solve any Linear Equation in One Variable
String Processing with Apache Commons Lang 3
Java Program to Apply DFS to Perform the Topological Sorting of a Directed Acyclic Graph
Spring Boot: Customize Whitelabel Error Page
Java Program to Represent Linear Equations in Matrix Form
Spring Cloud – Tracing Services with Zipkin
Using a Mutex Object in Java
Spring MVC Custom Validation