Find all the factors of a given number

Factors of a given number are the numbers from 1 till the number, for which the number is divisible. It means all these numbers divide the given number and give remainder 0.

Example: The factors of 24 are 1, 2, 3, 4, 6, 8, 12, 24


        public static List<int> DoGetFactors(int n)
        {
            List<int> factors = new List<int>();

            // every number is divisible by 1
            factors.Add(1);

            for (int i = 2; i < n; i++)
            {
                if (n % i == 0)
                {
                    factors.Add(i);
                }
            }

            // every number is divisible by itself
            factors.Add(n);

            return factors;
        }
        

How it works:

For a given number, we’ll iterate from 2 till the number (but not the number included) and divide the number with each iteration counter. If the remainder is a 0 (meaning the number is divisible by the current counter) we’ll add the counter to the list. Finally we’ll return the list of all stored counters till the number back. By rule of divisibility every number is always divisible by 1 and itself so we’ll skip those two numbers within our loop.

For a number 12:


12%2=0
12%3=0
12%4=0
12%5=2
12%6=0
12%7=5
12%8=4
12%9=3
12%10=2
12%11=1

Hence the return factors: 1,2,3,4,6,12

Ram
Ram

I'm a full-stack developer and a software enthusiast who likes to play around with cloud and tech stack out of curiosity. You can connect with me on Medium, Twitter or LinkedIn.

Privacy Overview
Referbruv

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.

Strictly Necessary Cookies

Strictly Necessary Cookie should be enabled at all times so that we can save your preferences for cookie settings.

3rd Party Cookies

This website uses Google Analytics to collect anonymous information such as the number of visitors to the site, and the most popular pages.

Keeping this cookie enabled helps us to improve our website.