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 String Conversions
How to Round a Number to N Decimal Places in Java
Java String to InputStream
Java Program to Check whether Directed Graph is Connected using BFS
Java Program to Implement Bresenham Line Algorithm
Java Program to Find ith Largest Number from a Given List Using Order-Statistic Algorithm
HandlerAdapters in Spring MVC
Extract links from an HTML page
Rest Web service: Filter và Interceptor với Jersey 2.x (P2)
Spring MVC Async vs Spring WebFlux
Setting the Java Version in Maven
Tìm hiểu về xác thực và phân quyền trong ứng dụng
Spring NoSuchBeanDefinitionException
Vector trong Java
A Quick Guide to Spring MVC Matrix Variables
Transactions with Spring and JPA
Spring Security Authentication Provider
Java Program to Find kth Smallest Element by the Method of Partitioning the Array
Spring Boot - Runners
Spring RestTemplate Request/Response Logging
Java Program to Implement Graham Scan Algorithm to Find the Convex Hull
Giới thiệu Design Patterns
Spring Boot - Introduction
Introduction to Netflix Archaius with Spring Cloud
Beans and Dependency Injection
Java Program to Create a Random Linear Extension for a DAG
Reversing a Linked List in Java
Service Registration with Eureka
Jackson Exceptions – Problems and Solutions
Guide to BufferedReader
Convert Hex to ASCII in Java
REST Web service: Basic Authentication trong Jersey 2.x