Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //program to find square root of a number without using square root function
- import java.util.Scanner;
- public class squareRoot{
- public static void main(String arg[]){
- boolean cont = true;
- do{
- Scanner sc = new Scanner(System.in);
- //taking input from the user
- System.out.print("Enter the Number whose square root needs to be found out : ");
- double number = sc.nextDouble();
- // if the number is less than 0 then ask user to enter another number
- while(number < 0){
- System.out.println("Please enter a positive number");
- System.out.print("Enter the Number whose square root needs to be found out : ");
- number = sc.nextDouble();
- }
- // if the number is 0 or 1 then the answer is also is also 0 or 1
- if(number == 0 || number == 1){
- System.out.print("The square root of the number " + number + " is " + number + "\n\n");
- continue;
- }
- //else take initial guess from the user
- System.out.print("Enter the Initial guess : ");
- double sqroot = sc.nextInt();
- //taking mod of the guess so as to make it smaller than the square
- sqroot = sqroot % number;
- findroot(number,sqroot);
- System.out.print("Do you want to enter another number (1/0) : ");
- int n = sc.nextInt();
- if(n == 0){
- cont = false;
- }
- }while(cont);
- }
- public static void findroot(double number, double sqroot){
- // setting answer to be accurate upto 6 decimal places
- // change this to get more accuracy
- double error = 0.000001;
- // calculating num
- double num = number/sqroot;
- // till the difference is greater than error keep taking average
- while(((num < sqroot) && (sqroot - num > error)) || ((num > sqroot)&&(num - sqroot > error))){
- // taking average
- sqroot = (sqroot + num)/2;
- num = number/sqroot;
- // if num and sqroot are equal then we directly print the answer
- if(num == sqroot){
- break;
- }
- }
- System.out.print("The square root of the number " + number + " is " + sqroot + "\n\n");
- }
- }
Add Comment
Please, Sign In to add comment