C# - Smallest number

25. July 2011 18:00

 

Another interview question which can be suitable for a test to perform some simple calculations to verify an answer. The question is to find the smallest positive number that is evenly divisible by all the numbers from 1 to 20.

You answer should look something like this.

 

 

static void Main(string[] args)
{
    DateTime Start = DateTime.Now;
    int Answer = 0;

    do
    {
        Answer++;
    } while (CanDiv(Answer, 20) == false);

    Console.WriteLine("Answer: {0}", Answer);

    Console.WriteLine("Time Taken: {0}", DateTime.Now - Start);
    Console.ReadLine();
}

static bool CanDiv(int value, int max)
{
    for (int i = max - 1; i > 0; i--)
        if (value % i != 0)
            return false;
    return true;
}

 

 

The CanDiv function could also do the same calculation with a for loop counting up. However it will result in taking longer to run.

 

static bool OldCanDiv(int value, int max)
{
    for (int i = 1; i < max; i++)
        if (value % i != 0)
            return false;
    return true;
}

 

E-mail Kick it! DZone it! del.icio.us Permalink


Comments (1) -

6/17/2013 7:48:25 PM #

for (int i = max - 1; i > 0; i--)

What's the point to check
if (value % i != 0)
for i=1?

should be:

for (int i = max - 1; i > 1; i--)

Jacek Ireland |