Java Program to find Square Root of a Number without sqrt

In Java, we have a Math.sqrt function that returns the square root of any given number. In this Java program, we will find the square root without using that sqrt function. As you see, we used the do while loop to find the square root.

package RemainingSimplePrograms;

import java.util.Scanner;

public class SqrRootOfNum1 {
	
	private static Scanner sc;
	
	public static void main(String[] args) {
		
		sc = new Scanner(System.in);
		
		System.out.print("Please Enter Any Number to find Square Root = ");
		double num = sc.nextDouble();
		
		double temp, squareroot;
		
		squareroot = num / 2;
		
		do {
			temp = squareroot;
			squareroot = (temp + (num / temp))/2;
		} while((temp - squareroot) != 0);
		
		System.out.println("\nThe Square Root of a Number without sqrt = " + squareroot);
	}
}
Java Program to find Square Root of a Number without sqrt

In this Java example, we are calculating the square of each member compared with the given number. If it is less than the given number, increment the value.

package RemainingSimplePrograms;

import java.util.Scanner;

public class SqrRootOfNum2 {
	private static Scanner sc;
	public static void main(String[] args) {
		sc = new Scanner(System.in);
		
		System.out.print("Please Enter Any Number to find Square Root = ");
		int num = sc.nextInt();
		
		int squareroot = squareRootWithoutsqrt(num);
		
		System.out.println("\nThe Square Root of a Number without sqrt = " + squareroot);
	}
	
	public static int squareRootWithoutsqrt(int num) {
		if(num < 2) {
			return num;
		}
		int mid, start = 1, end = num;
		while(start <= end) {
			mid = (start + end) /2;
			
			if(mid * mid == num) {
				return mid;
			} else if(mid * mid > num) {
				end = mid - 1;
			} else {
				start = mid + 1;
			}
		}
		return end;
	}
}
Please Enter Any Number to find Square Root = 986

The Square Root of a Number without sqrt = 31

Java Program to find Square Root of a Number without sqrt

In this Java example, we used the binary search to find the square root.

package RemainingSimplePrograms;

import java.util.Scanner;

public class SqrRootOfNum3 {
	private static Scanner sc;
	public static void main(String[] args) {
		sc = new Scanner(System.in);
		
		System.out.print("Please Enter Any Number to find Square Root = ");
		int num = sc.nextInt();
		
		int squareroot = squareRootWithoutsqrt(num);
		
		System.out.println("\nThe Square Root of a Number without sqrt = " + squareroot);
	}
	
	public static int squareRootWithoutsqrt(int num) {
		if(num < 2) {
			return num;
		}
		
		int sqrtVal = 1;
		while(sqrtVal * sqrtVal <= num) {
			sqrtVal++;
		}
		return sqrtVal - 1;
	}
}
Please Enter Any Number to find Square Root = 97

The Square Root of a Number without sqrt = 9