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 Binomial Heap
ETags for REST with Spring
Hướng dẫn Java Design Pattern – Singleton
Hướng dẫn sử dụng Java Reflection
An Introduction to ThreadLocal in Java
Java Program to Check Multiplicability of Two Matrices
Java Program to implement Bit Set
Java Program to Implement Shoelace Algorithm
Java Program to Implement First Fit Decreasing for 1-D Objects and M Bins
Hashtable trong java
The SpringJUnitConfig and SpringJUnitWebConfig Annotations in Spring 5
Java Program to Check whether Undirected Graph is Connected using DFS
Java Program to Implement Sparse Matrix
Java Program to Implement ScapeGoat Tree
Java Program to Find Transpose of a Graph Matrix
Introduction to Apache Commons Text
Guide to Selenium with JUnit / TestNG
Receive email using POP3
Java Program to Implement Ternary Search Algorithm
Using a Custom Spring MVC’s Handler Interceptor to Manage Sessions
Java Map With Case-Insensitive Keys
Java Program to Check Whether an Undirected Graph Contains a Eulerian Cycle
Hướng dẫn Java Design Pattern – Flyweight
Convert a Map to an Array, List or Set in Java
Java Program to Implement Interval Tree
An Intro to Spring Cloud Zookeeper
Java Program to Implement Control Table
Spring Boot - Service Components
Java Program for Topological Sorting in Graphs
Creating Docker Images with Spring Boot
Java Program to Implement Range Tree
Map to String Conversion in Java