Showing posts with label Interview. Show all posts
Showing posts with label Interview. Show all posts

December 27, 2012

InterView - Quickest Way to Find Prime Numbers


This week one of my college conducting interview for fresher candidates,
One question i have heard,

"Write a program to Find Prime.?"

Question on my mind, If that question asked on me, Am i capable to solve this in best way..?

That made the following program.


class Program
{
    static void Main(string[] args)
    {
        int limit = 1000;
        PrintPrimeNos(limit);
    }
 
    static void PrintPrimeNos(long limit)
    {
        // Any number must divide with 1 and itself
        // and Even number never be a prime number (Any even no at-least can able to divide by 2 )
        // So dividend start with 3 & incremented by 2
        // This will reduce no of iterations
        for (long dividend = 3; dividend < limit; dividend = dividend + 2)
        {
            bool IsPrimeNo = true;
 
            // Same as above
            // dividend / 2: Less than half of dividend only able to divide the dividend fully
            for (long divisor = 3; divisor < dividend / 2; divisor = divisor + 2)
            {
                if (dividend % divisor == 0)
                {
                    IsPrimeNo = false;
                    break;
                }
            }
 
            if (IsPrimeNo)
                Console.WriteLine(dividend);
        }
        Console.ReadLine();
    }
}

December 6, 2012

Interview - Quickest Way to Get nth Maximum Value From a Table

Now-a-days  "Query to find 2nd Maximum value  or Nth Maximum value from a table" are a common questions in interviews.

Here I'm given the best one to find nth max value from a table.
Below i mentioned 3 queries. 2 takes inbuild method, 1 Without using inbuild method

USE NorthWind
GO
 
WITH result AS 
( SELECT DENSE_RANK() OVER(ORDER BY UnitPrice DESC) AS 'SecondMaximum',* FROM Products )
SELECT * FROM result WHERE SecondMaximum = 2;
 
GO
 
WITH result AS 
( SELECT ROW_NUMBER() OVER(ORDER BY UnitPrice DESC) AS 'SecondMaximum',* FROM Products )
SELECT * FROM result WHERE SecondMaximum = 2;
 
GO
 
SELECT TOP 1 * FROM 
( SELECT TOP 2 * FROM Products ORDER BY UnitPrice DESC ) result 
ORDER BY UnitPrice ASC

the result is, the first one (DENSE_RANK) takes less time then remaining.


SecondMaximum value or Top value in subquery you can get nth maximum value

[ Hint: Here we can use "RANK" method instead of "DENSE_RANK" method, If the "UnitPrice" values are different. ]