Wednesday, March 9, 2016

Find the square root of the number

Code:

Method - 1:

using System;

public class Test
{
    public static void Main()
    {
        int n = 25;

        Console.WriteLine("Input: " + n);

        Console.WriteLine("Output:" + new Test().SquareRoot(n, 1, n));
    }

    public int SquareRoot(int n, int min, int max)
    {
        if(min > max)
        {
            return -1;
        }

        int value = (min + max) / 2;

        if (value * value == n)
        {
            return value;
        }
        else if (value * value > n)
        {
            return SquareRoot(n, min, value - 1);
        }
        else
        {
            return SquareRoot(n, value + 1, max);
        }
    }


}

Run Time: O(log n)

Method - 2:

using System;

public class Test
{
    public static void Main()
    {
        int n = 25;

        Console.WriteLine("Input: " + n);

        Console.WriteLine("Output:" + new Test().SquareRoot(n));
    }

    public int SquareRoot(int n)
    {
        for(int i = 1; i * i <= n ; i++)
        {
        if(i * i ==  n)
        {
        return i;
        }
        }
        
        return -1;
    }


}

Run Time: O(n^1/2)

Output:


Input: 25
Output:5

No comments:

Post a Comment