This is another quick code snippet to help those working through Project Euler problems. A very common part of a problem involves factors or the counting of factors. This snippet below will make quick work of getting a list of a given integer's factors.

Enjoy!

private static IEnumerable<int> GetFactors(int num)
{
//Given anumber (num), return a list of all of it's
//factors.
//We're going to grab this from both ends, since a given factor
//divided by our number will yield a second factor. for example,
//the factors of 6 can be expressed as:
// Given our first factor (1), and dividing 1 / 6, we get a second factor (6).
// Given our third factor (2), and dividing 2 / 6, we get a fourth factor (3).
for (int factor = 1; factor * factor <= num; factor++)
{
if (num % factor == 0)
{
yield return factor;
if (factor * factor != num)
yield return num / factor;
}
}
}

Posted on Saturday, February 27, 2010 3:11 PM | Back to top

Comments on this post: C# - Quickly determining the Factors of a given number

#re: C# - Quickly determining the Factors of a given number

One minor quibble:

maxnum is never defined anywhere. Is it an input parameter, or just an int?

#re: C# - Quickly determining the Factors of a given number

You're absolutely correct - forgot to change some variable names when I was pulling this out of my euler problem to make it more generic - went ahead and corrected it.

maxnum is never defined anywhere. Is it an input parameter, or just an int?

Thanks for the catch!