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:
Một số ký tự đặc biệt trong Java
Getting Started with GraphQL and Spring Boot
Introduction to Using Thymeleaf in Spring
wait() and notify() Methods in Java
Bootstrap a Web Application with Spring 5
Predicate trong Java 8
Java – Convert File to InputStream
Java Program to Implement Fenwick Tree
Spring Security OAuth2 – Simple Token Revocation
Java Program to Implement Multi-Threaded Version of Binary Search Tree
Guide to the Java ArrayList
Updating your Password
Spring MVC and the @ModelAttribute Annotation
Spring Boot - Admin Server
So sánh ArrayList và Vector trong Java
Spring Boot - Web Socket
Java Program to Implement the linear congruential generator for Pseudo Random Number Generation
The Modulo Operator in Java
More Jackson Annotations
Java Program to Use Boruvka’s Algorithm to Find the Minimum Spanning Tree
Java Program to Implement the Schonhage-Strassen Algorithm for Multiplication of Two Numbers
Java Program to Perform the Sorting Using Counting Sort
@Before vs @BeforeClass vs @BeforeEach vs @BeforeAll
HttpClient Connection Management
Kiểu dữ liệu Ngày Giờ (Date Time) trong java
Spring Webflux with Kotlin
Injecting Prototype Beans into a Singleton Instance in Spring
Java Program to Implement Stein GCD Algorithm
Convert Hex to ASCII in Java
Static Content in Spring WebFlux
Java Program to Check Whether an Undirected Graph Contains a Eulerian Cycle
Spring Cloud – Tracing Services with Zipkin