Facebook
4.6 of 5 638 reviews
www.facebook.com Menlo Park, CA 5000+ Employees

Facebook Software Engineer Intern Interview Question (student candidate)

"Write a function that returns the square root of a number (obviously without using any sort of built-in square root function)."
Add Tags [?]
Answer Flag Question

Part of a Software Engineer Intern Interview Review - one of 1,005 Facebook Interview Reviews

Answers & Comments

2
of 2
votes
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 Flag Response
3
of 3
votes
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 Flag Response
0
of 6
votes
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 Flag Response
0
of 0
votes
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 Flag Response

To comment on this question, Sign In with Facebook or Sign Up


Tags are like keywords that help categorize interview questions that have something in common.

Glassdoor is your free inside look at Facebook interview questions and advice. All interview reviews posted anonymously by Facebook employees and interview candidates.