package com.kartik;
import java.util.Scanner;
public class SquareRoot {
public static double calculateSqrt (int n) {
double rootValue = 1.00;
double num = n;
for (int i = 0; i < n; i++) {
rootValue = 0.5 * (rootValue + num/rootValue);
}
//To make only 3 digit available after decimal point
int returnValue = (int)(rootValue * 1000);
rootValue = returnValue;
rootValue /=1000;
System.out.println("Root Value Calculated : " + rootValue);
// System.out.println("Root Value By InBuild Method Method : " + Math.sqrt(n));
return rootValue;
}
public static double calculateSqare (int n) {
double square=0;
square=n*n;
return square;
}
public static void main (String[] args) {
int n;
Scanner input = new Scanner (System.in);
System.out.println("Enter Number to find its square root-");
n = input.nextInt();
double a=calculateSqrt(n);
int floorValue= (int) (a);
int cellingValue= (int) (a);
if (cellingValue < a) cellingValue++;
// int floorValue=(int) Math.floor(a);
//int cellingValue=(int)Math.ceil(a);
if(n-calculateSqare(floorValue)>calculateSqare(cellingValue)-n){
System.out.println(+n+" Nearest square value is "+calculateSqare(cellingValue));
}else{
System.out.println(+n+" Nearest square value is "+calculateSqare(floorValue));
}
}
}
out put :
Enter Number to find its square root-
8
Root Value Calculated : 2.828
8 Nearest square value is 9.0
import java.util.Scanner;
public class SquareRoot {
public static double calculateSqrt (int n) {
double rootValue = 1.00;
double num = n;
for (int i = 0; i < n; i++) {
rootValue = 0.5 * (rootValue + num/rootValue);
}
//To make only 3 digit available after decimal point
int returnValue = (int)(rootValue * 1000);
rootValue = returnValue;
rootValue /=1000;
System.out.println("Root Value Calculated : " + rootValue);
// System.out.println("Root Value By InBuild Method Method : " + Math.sqrt(n));
return rootValue;
}
public static double calculateSqare (int n) {
double square=0;
square=n*n;
return square;
}
public static void main (String[] args) {
int n;
Scanner input = new Scanner (System.in);
System.out.println("Enter Number to find its square root-");
n = input.nextInt();
double a=calculateSqrt(n);
int floorValue= (int) (a);
int cellingValue= (int) (a);
if (cellingValue < a) cellingValue++;
// int floorValue=(int) Math.floor(a);
//int cellingValue=(int)Math.ceil(a);
if(n-calculateSqare(floorValue)>calculateSqare(cellingValue)-n){
System.out.println(+n+" Nearest square value is "+calculateSqare(cellingValue));
}else{
System.out.println(+n+" Nearest square value is "+calculateSqare(floorValue));
}
}
}
out put :
Enter Number to find its square root-
8
Root Value Calculated : 2.828
8 Nearest square value is 9.0