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:
Converting between an Array and a List in Java
Java Program to Check Whether an Undirected Graph Contains a Eulerian Path
Arrays.asList vs new ArrayList(Arrays.asList())
Spring Boot - OAuth2 with JWT
Introduction to the Java NIO Selector
Java Program to Implement LinkedHashSet API
Request a Delivery / Read Receipt in Javamail
Java Program to Implement Counting Sort
Introduction to Project Reactor Bus
How to Remove the Last Character of a String?
Adding Shutdown Hooks for JVM Applications
Giới thiệu HATEOAS
Java Program to Implement Knight’s Tour Problem
How to Read a File in Java
Lớp Properties trong java
Java Program to Find Number of Spanning Trees in a Complete Bipartite Graph
Spring Boot - CORS Support
Spring Boot - Admin Client
Java Program to Implement Insertion Sort
Guide to java.util.Formatter
Java Program to Implement Kosaraju Algorithm
Java Program to Implement the Monoalphabetic Cypher
Kết hợp Java Reflection và Java Annotations
Java Program to Check whether Undirected Graph is Connected using DFS
So sánh HashMap và HashSet trong Java
Guide to Guava Table
Login For a Spring Web App – Error Handling and Localization
Java Program to Implement Queue using Linked List
Java Program to Check Multiplicability of Two Matrices
Tiêu chuẩn coding trong Java (Coding Standards)
Check If a File or Directory Exists in Java
Java Program to Represent Linear Equations in Matrix Form