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 Boot - Apache Kafka
Converting String to Stream of chars
Quick Guide to Spring Controllers
So sánh HashMap và Hashtable trong Java
Functional Interface trong Java 8
Tránh lỗi NullPointerException trong Java như thế nào?
Java Program to Implement Double Ended Queue
Hướng dẫn Java Design Pattern – Command
Spring Cloud – Bootstrapping
Notify User of Login From New Device or Location
Java Program to Generate Randomized Sequence of Given Range of Numbers
Java Program to Find the Median of two Sorted Arrays using Binary Search Approach
Java Program to Check the Connectivity of Graph Using BFS
Java Program to Encode a Message Using Playfair Cipher
Java Program to Search Number Using Divide and Conquer with the Aid of Fibonacci Numbers
Jackson Unmarshalling JSON with Unknown Properties
A Quick Guide to Spring Cloud Consul
Consuming RESTful Web Services
Using JWT with Spring Security OAuth
Hướng dẫn Java Design Pattern – Builder
Java Program to Implement Graham Scan Algorithm to Find the Convex Hull
Java Program to Implement Find all Back Edges in a Graph
Chương trình Java đầu tiên
Simultaneous Spring WebClient Calls
Java Program to Perform LU Decomposition of any Matrix
Java Program to Implement Kosaraju Algorithm
A Quick Guide to Spring MVC Matrix Variables
Java Program to Construct an Expression Tree for an Prefix Expression
Java Program to Implement Iterative Deepening
Checking for Empty or Blank Strings in Java
The SpringJUnitConfig and SpringJUnitWebConfig Annotations in Spring 5
OAuth2 for a Spring REST API – Handle the Refresh Token in Angular