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();
}
}
 

I guess you would fail.
ReplyDelete1. A good developer divides responsibilities: getting prime numbers (1) and output of them (2)
2. A good developer would create a stream which could be used with LINQ (use of yield)