Muckeypuck Muckeypuck - 3 months ago 6
C# Question

All numbers less than or divisible by Seven

So i had an interview question: Write a function that takes a number and returns all numbers less than or divisible by 7

private List<int> GetLessThanOrDivisbleBySeven(int num)
{
List<int> ReturnList = new List<int>();

for(int i = 0; i <= num; i++)
{
if(i <7 || i % 7 == 0)
{
ReturnList.Add(i);
}
}

return ReturnList;
}


So far so good. The follow up question was: Let's say that call was being made 10s of thousands of times an hour. How could you speed it up?

I said if you knew what your queue was you could break up your queue and thread it. That got me some points i feel. However, he wanted to know if there was anything in the function i could do.

I came up with the idea to test if the num was greater than 7. if so initialize the list with 1 - 7 and start the loop int i = 8 which i think was ok but is there another way i am missing?

Answer

If you want to speed it up without caching, you can just increment i by 7 to get all numbers divisible by 7, it will be something like this:

        static private List<int> GetLessThanOrDivisbleBySeven(int num) {
            List<int> ReturnList;
            int i;
            if (num <= 7) {
                ReturnList = new List<int>();
                for (i = 0; i <= num; i++) {
                    ReturnList.Add(i);
                }
                return ReturnList;
            }

            ReturnList = new List<int> { 0, 1, 2, 3, 4, 5, 6 };
            i = 7;
            while (i <= num) {
                ReturnList.Add(i);
                i += 7;
            }

            return ReturnList;
        }