Saturday, October 20, 2012

Mathematics6

Q6. Find the square root of given number n without using Math.sqrt() function and multiplication operation? Return the largest integer less than or equal to square root of given number n. For example:
getSquareRoot(16) = 4
getSquareRoot(17) = 4
getSquareRoot(25) = 5
getSquareRoot(26) = 5 
getSquareRoot(36) = 6

Answer: 
  • Hint: Sum of 1st n odd integers = square of n.
  • Example:
    • 1 = 1 = sqr(1)
    • 1 + 3 + 5 = 9 = sqr(3)
    • 1 + 3 + 5 + 7= 16 = sqr(4)

public class Mathematics6 {
    public static int getSquareRoot(int n) {
        int squareRoot = 0;
        int sum = 0;
        int oddNumber = 1;

        while (sum <= n) {
            sum += oddNumber;
            oddNumber += 2;
            squareRoot++;
        }
        return (squareRoot-1);
    }

    public static void main(String[] args) {
        System.out.println(getSquareRoot(12));
        System.out.println(getSquareRoot(624));
        System.out.println(getSquareRoot(625));
        System.out.println(getSquareRoot(626));
    }
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.