Friday, December 19, 2014

Finding nth root in Java


import java.util.*;

public class Root {

static double nthRoot(int a, int b) {
     return Math.pow(a, 1.0 / b);
  }


public static void main(String[] args) {
       Scanner in = new Scanner(System.in);
       int a, b, c;
       System.out.println("Enter the number to calculate the root:");
       a = in.nextInt();
       System.out.println("Enter the base to calculate the root: ");
       b = in.nextInt();
       System.out.println("Enter the precision to calculate the root: ");  
         c = in.nextInt();
       double sum;
       sum = nthRoot(a, b);
       System.out.println(b + "th root of " + a +" is: " + String.format("%."+c+"f\n", sum)); // The highlighted code is to implement the variable precision which will depend on the value of integer c
  }
}                        

Input #1
Enter the number to calculate the root:
81
Enter the base to calculate the root:
4
Enter the precision to calculate the root:
5

Output #1
4th root of 81 is: 3.00000

Input #2
Enter the number to calculate the root:
2
Enter the base to calculate the root:
2
Enter the precision to calculate the root:
3
Output #2
2th root of 2 is: 1.414

Input #3
Enter the number to calculate the root:
64
Enter the base to calculate the root:
3
Enter the precision to calculate the root:
7
Output #3

3th root of 64 is: 4.0000000

                                                                                                

No comments:

Post a Comment