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:
Spring Data JPA @Modifying Annotation
Updating your Password
Java Program to Check whether Graph is a Bipartite using 2 Color Algorithm
Java Program to Implement Hash Tables Chaining with Doubly Linked Lists
Vector trong Java
Weak References in Java
Spring Boot - Hystrix
Java Program to Find Shortest Path Between All Vertices Using Floyd-Warshall’s Algorithm
Spring Boot - Tomcat Deployment
Tránh lỗi NullPointerException trong Java như thế nào?
Java Program to Implement Splay Tree
Spring RestTemplate Error Handling
Java – Write a Reader to File
Pagination and Sorting using Spring Data JPA
Biểu thức Lambda trong Java 8 – Lambda Expressions
Java Optional as Return Type
Marker Interface trong Java
The Registration API becomes RESTful
Java – Byte Array to Reader
Getting the Size of an Iterable in Java
Hướng dẫn Java Design Pattern – Object Pool
Java Program to Find Nearest Neighbor for Static Data Set
Java Program to Repeatedly Search the Same Text (such as Bible by building a Data Structure)
Giới thiệu Google Guice – Binding
Java Program to Check whether Undirected Graph is Connected using BFS
Use Liquibase to Safely Evolve Your Database Schema
Java Program to Give an Implementation of the Traditional Chinese Postman Problem
Hướng dẫn sử dụng Printing Service trong Java
What is Thread-Safety and How to Achieve it?
Java Program to Implement Pairing Heap
Java Convenience Factory Methods for Collections
A Quick Guide to Spring MVC Matrix Variables