Facebook

  www.facebook.com
  www.facebook.com

Interview Question

Software Engineer Intern Interview(Student Candidate)

Write a function that returns the square root of a number

  (obviously without using any sort of built-in square root function).
Answer

Interview Answer

4 Answers

2

It might not be the best code, and might be possible to be optimized, but it returns the floor of the sqrt(n):
public class SquareRoot {

    public static void main(String[] args) {
        System.out.println(squareRoot(300));
    }

    private static int squareRoot(int i) {
        int res = 1;
        while (true) {
            if (res * res < i) {
                res *= 2;
            } else {
                break;
            }
        }
        int low = res / 2;
        int high = res;
        while (low < high) {
            int mid = (low + high) / 2;
            res = mid;
            if (mid * mid < i) {
                low = mid + 1;
            } else if (mid * mid == i) {
                res = mid;
                break;
            } else {
                high = mid - 1;
                res = mid;
            }
        }
        while (res * res < i) {
            res++;
        }
        while (res * res > i) {
            res--;
        }
        return res;
    }
}

Ahmed on Feb 20, 2013
3

This solution uses Newton's Method to converge on the result quickly.

  public static void main(String[] args)
  {
      System.out.println(squareRoot(300));
  }

  private static double squareRoot(int i)
  {
      while(0.0001 < Math.abs((guess * guess) - num))
      {
          guess = (guess + (num / guess)) / 2;
      }
      return guess;
  }

Sam on Feb 25, 2013
0

int sqrt(num) {
    int sum = 0;
    if(num == 0) return 0;
    if (num == 1) return 1;

    for(i=0; i<num; i++) {
        sum = sum + num;
    }

    return(sum)
}

Anonymous on Mar 3, 2013
0

public static void main(String[] args) {
        // TODO Auto-generated method stub
        int input = 5;
        double guess = input/2;
        double root = 0.0;
        for(int i =0; i<=10;i++)
        {
            root = input/guess;
            guess = (guess+root)/2;
        }
        System.out.println(root);

Aravind on Apr 27, 2013

Add Answers or Comments

To comment on this, Sign In or Sign Up.