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 Map With Case-Insensitive Keys
Java Program to Perform Searching Using Self-Organizing Lists
Intro to Spring Boot Starters
Java Program to Implement Depth-limited Search
Java Program to Implement Jarvis Algorithm
How to Get All Spring-Managed Beans?
Java Program to Perform Inorder Non-Recursive Traversal of a Given Binary Tree
Java – Reader to String
Java Program to Implement Sorted Array
Check If a String Is Numeric in Java
New Features in Java 12
Easy Ways to Write a Java InputStream to an OutputStream
An Intro to Spring Cloud Vault
Tính đa hình (Polymorphism) trong Java
Java Program to Implement HashTable API
Java Optional as Return Type
Guide to Spring 5 WebFlux
Mapping Nested Values with Jackson
Join and Split Arrays and Collections in Java
Java Program to Implement Gauss Jordan Elimination
Một số tính năng mới về xử lý ngoại lệ trong Java 7
Hướng dẫn Java Design Pattern – Interpreter
Setting the Java Version in Maven
So sánh HashMap và Hashtable trong Java
Spring REST API + OAuth2 + Angular
Convert Time to Milliseconds in Java
Convert Hex to ASCII in Java
Java Program to Implement HashSet API
Comparing Dates in Java
Java Program to Find the Median of two Sorted Arrays using Binary Search Approach
LIKE Queries in Spring JPA Repositories
Spring – Injecting Collections