Dex
Dex

Reputation: 33

How to lower program execution time?

How do I reduce the following program execution time:

using System;
using System.Diagnostics;
class LeastMM
{
    static void Main()
    {
        Stopwatch sw = new Stopwatch();
        sw.Start();
        byte[] nums = new byte[5];
        for (byte i = 0; i < nums.Length; i++)
        {
            nums[i] = byte.Parse(Console.ReadLine());
        }
        short? lmm = null;
        //uint currentI = 1;
        byte divisors = 0;
        //for (uint i = 1; i < nums.Length; i++) Console.WriteLine("{0} {1} ", i, nums[i]);
        for (short i = 1; ; i++)
        {
            divisors = 0;
            for (byte j = 0; j < nums.Length; j++)
            {
                if (i % nums[j] == 0) divisors++;
            }
            if (divisors >= 3) 
            {
                lmm = i;
                break;
            }
        }
        Console.WriteLine(lmm);
        sw.Stop();
        Console.WriteLine();
        Console.WriteLine(sw.Elapsed.Seconds + " or " +"0."+sw.Elapsed.Milliseconds);
    }
}

Execution time has to be < 0.25 seconds. I tried not to use loops but four different variables - a, b, c, d, e, also tried to use the smallest decimal type possible. None of these worked. The purpose of this program is to find the least majority divisor between at least 3 of the provided numbers. i.e. the least majority divisor of 1, 2, 3, 4, 5 is 4 because it is divisable by 4, 2, and 1. The numbers are in the range of 1 to 100 inclusive.

Upvotes: 0

Views: 1112

Answers (1)

user27414
user27414

Reputation:

When I run this I get 0.0024ms execution time for input = 1,2,3,4,5 -- if I move the timing code to after the ReadLine loop. My PC might be a lot faster than yours, but I can't imagine getting > 0.25 seconds even if you run this on a Speak-n-Spell.

Timing the user input is just plain crazy. If this is being timed by something external, are you sure the inputs are supposed to be read line-by-line, and not passed in via the command line?

Upvotes: 1

Related Questions