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 Range Tree
JUnit 5 @Test Annotation
Java Program to Implement Graph Coloring Algorithm
A Guide to Java 9 Modularity
Java Program to Describe the Representation of Graph using Adjacency List
Java Program to Implement Regular Falsi Algorithm
Java Program to Implement Skew Heap
Immutable Map Implementations in Java
Biểu thức Lambda trong Java 8 – Lambda Expressions
Copy a List to Another List in Java
Optional trong Java 8
Quick Guide to Spring Controllers
Registration – Password Strength and Rules
Tính trừu tượng (Abstraction) trong Java
Vấn đề Nhà sản xuất (Producer) – Người tiêu dùng (Consumer) và đồng bộ hóa các luồng trong Java
Lớp lồng nhau trong java (Java inner class)
Primitive Type Streams in Java 8
JUnit5 @RunWith
Kiểu dữ liệu Ngày Giờ (Date Time) trong java
Java Program to Implement Floyd Cycle Algorithm
Introduction to Using FreeMarker in Spring MVC
Setting Up Swagger 2 with a Spring REST API
Hướng dẫn Java Design Pattern – Observer
LinkedList trong java
How to Read a Large File Efficiently with Java
The Dining Philosophers Problem in Java
Enum trong java
Spring Data JPA and Null Parameters
Control Structures in Java
Java Program to Implement Weight Balanced Tree
Spring WebClient and OAuth2 Support
Using a Spring Cloud App Starter