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 Find Transitive Closure of a Graph
Notify User of Login From New Device or Location
Java Program to Find the Mode in a Data Set
Java Program to Implement Stack
Java Program to Perform Polygon Containment Test
Reactive WebSockets with Spring 5
Lập trình hướng đối tượng (OOPs) trong java
Hướng dẫn Java Design Pattern – Decorator
Introduction to Spring Cloud OpenFeign
Transaction Propagation and Isolation in Spring @Transactional
Set Interface trong Java
Using a List of Values in a JdbcTemplate IN Clause
Cài đặt và sử dụng Swagger UI
Java 8 Stream findFirst() vs. findAny()
Java Program to Implement Suffix Array
Abstract class và Interface trong Java
Java Program to Solve Knapsack Problem Using Dynamic Programming
Posting with HttpClient
Các kiểu dữ liệu trong java
How To Serialize and Deserialize Enums with Jackson
An Introduction to Java.util.Hashtable Class
Creating a Generic Array in Java
Java Program to Implement Quick Sort Using Randomization
How to use the Spring FactoryBean?
Java Program to Implement Ternary Tree
Pagination and Sorting using Spring Data JPA
Test a REST API with Java
Java – Combine Multiple Collections
Java Program to Show the Duality Transformation of Line and Point
Java – String to Reader
Primitive Type Streams in Java 8
Java Program to Perform Postorder Non-Recursive Traversal of a Given Binary Tree