In: Computer Science
In this assignment, we will implement a square root approximater and then an nth root approximater. Recall that the nth root of x is the number when raised to the power n gives x. We learned in class that we can use the concepts of binary search to approx imate the square root of a number, and we can continue this logic to approximate the nth square root. Please look at Lecture Notes 03, section 4 for a little more detail. We're going to use the concepts of binary search to try and approximate nding the square root and nding the nth root.
You may not use any library functions for these question, except DecimalFormat.
In this assignment, we will implement a square root approximater and then an nth root approximater. Recall that the nth root of x is the number when raised to the power n gives x. We learned in class that we can use the concepts of binary search to approx imate the square root of a number, and we can continue this logic to approximate the nth square root. Please look at Lecture Notes 03, section 4 for a little more detail. We're going to use the concepts of binary search to try and approximate nding the square root and nding the nth root. You may not use any library functions for these question, except DecimalFormat.
Program plan:
Square root of n:
pth root of n:
Program with sample main():
import java.io.*;
import java.util.*;
class Roots
{
static double root2(int n){
int low = 0, high = n;
int mid;
double root = 0.0;
while(low<high){
mid =
(low+high)/2;
//System.out.println(low);
//System.out.println(mid);
//System.out.println(high);
if(mid*mid==n){
root = mid;
break;
}
else
if(mid*mid<n){
low = mid+1;
}
else{
high = mid-1;
}
root =
mid;
}
double decimal = 0.1;
int i = 0;
while(i<13){
while(root*root<=n){
root += decimal;
}
root -=
decimal;
decimal /=
10;
i+=1;
}
return root;
}
static double rootn(int n, int p){
int low = 0, high = n;
int mid;
double root = 0.0;
while(low<high){
mid =
(low+high)/2;
//System.out.println(low);
//System.out.println(mid);
//System.out.println(high);
if(Math.pow(mid,n)==n){
root = mid;
break;
}
else
if(Math.pow(mid,n)<n){
low = mid+1;
}
else{
high = mid-1;
}
root =
mid;
}
double decimal = 0.1;
int i = 0;
while(i<13){
while(Math.pow(root,n)<=n){
root += decimal;
}
root -=
decimal;
decimal /=
10;
i+=1;
}
return root;
}
public static void main(String[] args){
System.out.print("square root of
28: ");
System.out.println(root2(28));
System.out.print("5th root of 28:
");
System.out.println(rootn(28,5));
}
}
Sample output: