w3resource

Java: Find the square root of a number using Babylonian method


Babylonian Square Root

Write a Java program to find the square root of a number using the Babylonian method.

Sample Solution:

Java Code:

import java.util.*;
public class solution {	
  public static float square_Root(float num) 
    { 
        float a = num; 
        float b = 1; 
        double e = 0.000001; 
        while (a - b > e) { 
            a = (a + b) / 2; 
            b = num / a; 
        } 
        return a; 
    } 
 
   public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.print("Input an integer: ");
        int num = scan.nextInt();
        scan.close(); 
		System.out.println("Square root of a number using Babylonian method: "+square_Root(num));		
		}
 }

Sample Output:

 Input an integer:  25
Square root of a number using Babylonian method: 5.0

Flowchart:

Flowchart: Find the square root of a number using Babylonian method.

For more Practice: Solve these Related Problems:

  • Write a Java program to calculate the square root of a number using the Babylonian method with a given tolerance.
  • Write a Java program to implement the Babylonian method recursively and count the iterations needed for convergence.
  • Write a Java program to compare the Babylonian square root result with Math.sqrt over various test cases.
  • Write a Java program to simulate the Babylonian square root algorithm using tail recursion.

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Java program to find the length of the longest sequence of zeros in binary representation of an integer.
Next: Write a Java program to multiply two integers without using multiplication, division, bitwise operators, and loops.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.