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 Implement Disjoint Sets
RestTemplate Post Request with JSON
Java Program to Implement Rope
Java Program to Implement the Checksum Method for Small String Messages and Detect
Java Program to implement Associate Array
Spring Webflux and CORS
Spring Boot - Unit Test Cases
Weak References in Java
Spring Security and OpenID Connect
Test a REST API with Java
Java Program to Implement ScapeGoat Tree
Java Program to Implement the linear congruential generator for Pseudo Random Number Generation
Extra Login Fields with Spring Security
Semaphore trong Java
Guide to PriorityBlockingQueue in Java
Converting Java Date to OffsetDateTime
Java Program to Implement Shunting Yard Algorithm
An Intro to Spring Cloud Vault
Java 8 StringJoiner
Java Program to Implement Counting Sort
Logout in an OAuth Secured Application
Hướng dẫn Java Design Pattern – Intercepting Filter
Collect a Java Stream to an Immutable Collection
Java Program to Generate All Subsets of a Given Set in the Gray Code Order
Java Program to Use Dynamic Programming to Solve Approximate String Matching
Java Program to Use Boruvka’s Algorithm to Find the Minimum Spanning Tree
Java Program to implement Sparse Vector
Functional Interface trong Java 8
Java Program to add two large numbers using Linked List
Quick Guide on Loading Initial Data with Spring Boot
Java Program to Perform Preorder Recursive Traversal of a Given Binary Tree
Java Program to Perform Encoding of a Message Using Matrix Multiplication